Last active
January 29, 2025 05:16
-
-
Save chriszarate/5092641 to your computer and use it in GitHub Desktop.
Native JavaScript function to get all *text* nodes contained in a selection object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get all *text* nodes contained in a selection object. | |
// Adapted from code by Tim Down. | |
// http://stackoverflow.com/questions/4398526/how-can-i-find-all-text-nodes-between-to-element-nodes-with-javascript-jquery | |
function getTextNodesBetween(selection) { | |
var range = selection.getRangeAt(0), rootNode = range.commonAncestorContainer, | |
startNode = range.startContainer, endNode = range.endContainer, | |
startOffset = range.startOffset, endOffset = range.endOffset, | |
pastStartNode = false, reachedEndNode = false, textNodes = []; | |
function getTextNodes(node) { | |
var val = node.nodeValue; | |
if(node == startNode && node == endNode && node !== rootNode) { | |
if(val) textNodes.push(val.substring(startOffset, endOffset)); | |
pastStartNode = reachedEndNode = true; | |
} else if(node == startNode) { | |
if(val) textNodes.push(val.substring(startOffset)); | |
pastStartNode = true; | |
} else if(node == endNode) { | |
if(val) textNodes.push(val.substring(0, endOffset)); | |
reachedEndNode = true; | |
} else if(node.nodeType == 3) { | |
if(val && pastStartNode && !reachedEndNode && !/^\s*$/.test(val)) { | |
textNodes.push(val); | |
} | |
} | |
for(var i = 0, len = node.childNodes.length; !reachedEndNode && i < len; ++i) { | |
getTextNodes(node.childNodes[i]); | |
} | |
} | |
getTextNodes(rootNode); | |
return textNodes; | |
} | |
// Lazy Range object detection. | |
function isRange(obj) { | |
return ('type' in obj && obj.type === 'Range'); | |
} | |
// Good-enough Range object comparison. | |
function rangeChange(data1, data2) { | |
return (data1.type !== data2.type || data1.focusNode !== data2.focusNode || data1.focusOffset !== data2.focusOffset); | |
} |
FYI: I have modified the code to my needs, and it seems that the if(node !== sumterDialog)
isn't needed and should be removed.
@michaelts1 Thanks, removed in gist
This doesn't get nodes at all, it gets the string contents.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sumterDialog?