Instantly share code, notes, and snippets.

Embed
What would you like to do?
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) {
if(node !== sumterDialog) 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

This comment has been minimized.

Copy link

agamemnus commented Dec 30, 2018

sumterDialog?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment