Skip to content

Instantly share code, notes, and snippets.

@naveen17797
Created March 8, 2020 06:17
Show Gist options
  • Save naveen17797/9bcecc197d83564c1f2becd777b8dd5b to your computer and use it in GitHub Desktop.
Save naveen17797/9bcecc197d83564c1f2becd777b8dd5b to your computer and use it in GitHub Desktop.
applies highlighting with a inline element recursively
function highlightNodes(el, tagName) {
for ( let element of el.childNodes ) {
if ( element.childNodes.length === 0 && element.nodeType === Node.TEXT_NODE) {
const newChild = document.createElement(tagName)
newChild.innerText = element.nodeValue
element.parentElement.replaceChild(newChild, element)
}
else {
highlightNodes(element, tagName)
}
}
}
// No spaces should be present in the source html
const el = document.getElementById("foo")
highlightNodes(el, "i")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment