Skip to content

Instantly share code, notes, and snippets.

@cmilfont
Created June 28, 2016 10:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmilfont/728236db8e23b4046e249425c2f12502 to your computer and use it in GitHub Desktop.
Save cmilfont/728236db8e23b4046e249425c2f12502 to your computer and use it in GitHub Desktop.
getTextNodesIn = (node) => {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, this.getTextNodesIn(children[i]));
}
}
return textNodes;
}
setSelectionRange = (el, start, end) => {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(el);
var textNodes = this.getTextNodesIn(el);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount
&& (start < endCharCount ||
(start == endCharCount && i <= textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd("character", end);
textRange.moveStart("character", start);
textRange.select();
}
}
@RollerIn
Copy link

Hi,
can you share some logic to get all child nodes and creating range of highlight text on web ?
scenario: when user select some text and do highlight on web , I want to validate that text range and elment rect
objHighlightOverlay.clientWidth and rangItem.width

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