Skip to content

Instantly share code, notes, and snippets.

@chriszarate
Last active April 1, 2023 13:45
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.
// 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);
}
@agamemnus
Copy link

sumterDialog?

@michaelts1
Copy link

FYI: I have modified the code to my needs, and it seems that the if(node !== sumterDialog) isn't needed and should be removed.

@chriszarate
Copy link
Author

@michaelts1 Thanks, removed in gist

@AntonOfTheWoods
Copy link

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