Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Last active November 27, 2022 04:38
Show Gist options
  • Save Shaddyjr/eed8286c87493e39ed51eaf905380924 to your computer and use it in GitHub Desktop.
Save Shaddyjr/eed8286c87493e39ed51eaf905380924 to your computer and use it in GitHub Desktop.
// video: https://youtu.be/wRbyX9sRZ9g
////////////
// CONFIG //
////////////
const termsAndColors = [
["how", "yellow"],
["javaScript", "LightPink"],
["works", "CornflowerBlue"],
]
// More named colors here: https://www.w3schools.com/colors/colors_names.asp
const caseSensitive = false
/////////////////////////////////
// Main Logic after this point //
/////////////////////////////////
// https://stackoverflow.com/questions/10730309/find-all-text-nodes-in-html-page
// sort in reverse order for better highlighting
const sortedTermsAndColors = termsAndColors.sort().reverse()
// For each word
for (const [searchWord, color] of termsAndColors){
let textNode
// create a tree walker to "walk" through all elements of the given type (textNode)
const walk = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false)
// create set of all unique parent nodes with text matching the give search word
const matchingParents = new Set()
// create regular expression that will be used to find text matches
// https://www.regextester.com/99992
const re = new RegExp(`(?<!</?[^>]*|&[^;]*)(${searchWord})`, caseSensitive ? "g" : "gi")
while(textNode=walk.nextNode()){
const parent = textNode.parentElement
if(['SCRIPT','STYLE'].includes(parent.tagName)) continue // ignore certain tags
// if textNode's data contain the searchWord, add it's parent to matchingParents set
if(re.test(textNode.data)){
matchingParents.add(parent)
}
}
// Create styled span as text, with matching substring as content
const spanString = `<span style="background-color:${color};">$1</span>`
for(const parent of matchingParents){
// Replace the text with span
parent.innerHTML = parent.innerHTML.replace(re, spanString)
}
}
console.log("DONE!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment