Skip to content

Instantly share code, notes, and snippets.

@ndvbd
Created March 7, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ndvbd/8321f5ba27225b220f384d9996abdda8 to your computer and use it in GitHub Desktop.
Save ndvbd/8321f5ba27225b220f384d9996abdda8 to your computer and use it in GitHub Desktop.
wrapWordSegmentWithElement | Parse the text out of a DOM element, and wrap a specific part of the text with a supplied wrapper element
/**
* This wraps the extracted text segment with a parent wrapper element.
* If the desired text segement is spread around few nodes, than it will wrap
* EACH one of the nodes with the same parent wrapper.
* As always, the startPosition is inclusive and the endPosition is exclusive
* rootNode - must be a DOM element (not a jquery element)
*/
function wrapWordSegmentWithElement(rootNode, startPosition, endPosition, emptyWrapperElement){
var n, text='', walk=document.createTreeWalker(rootNode, NodeFilter.SHOW_TEXT, null, false);
while (n = walk.nextNode()) {
var nodeStartInclusive = text.length;
var nodeEndExclusive = text.length+n.nodeValue.length;
text += n.nodeValue; // nodeValue, when it's not a jquery element
if (startPosition < nodeEndExclusive && endPosition > nodeStartInclusive){ // If we have an overlap
var clonedWrapperElement = emptyWrapperElement.cloneNode(true);
var currentNodeText = n.nodeValue;
var part1Text = currentNodeText.substring(0, Math.max(0, startPosition - nodeStartInclusive ));
var part2Text = currentNodeText.substring(Math.max(0, startPosition - nodeStartInclusive) , Math.min(currentNodeText.length, endPosition - nodeStartInclusive ));
var part3Text = currentNodeText.substring(Math.min(currentNodeText.length, endPosition - nodeStartInclusive ) , currentNodeText.length);
if (part3Text.length > 0) {
var t = document.createTextNode(part3Text);
$(t).insertAfter($(n));
}
if (part2Text.length > 0) {
$(clonedWrapperElement).append(part2Text);
$(clonedWrapperElement).insertAfter($(n));
}
if (part1Text.length > 0) {
var t = document.createTextNode(part1Text);
$(t).insertAfter($(n));
}
$(n).remove();
}
}
return text;
} // EOF wrapWordSegmentWithElement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment