Created
April 13, 2023 04:51
-
-
Save FSou1/c84ae03bdaa4128a97cb52aeb2dd1c9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://js-cqdfne.stackblitz.io/ | |
highlightNode(document.body, 'angular'); | |
function highlightNode(root, word) { | |
const textNodes = textNodesUnder(root); | |
console.log('Found nodes: ' + textNodes.length, textNodes); | |
const matchingNodes = textNodes | |
.filter((node) => new RegExp(word, 'gi').test(node.nodeValue)) | |
.map((node) => [node, new RegExp(word, 'gi').exec(node.nodeValue)]); | |
console.log('Matching nodes: ' + matchingNodes.length, matchingNodes); | |
} | |
function replaceWord(node, word) { | |
const highlightTag = 'em'; | |
const highlightClassName = 'highlighted'; | |
let match = document.createElement(highlightTag); | |
match.className = highlightClassName; | |
match.appendChild(document.createTextNode(word)); | |
match.style.backgroundColor = 'yellow'; | |
var after = node.splitText(regs.index); | |
after.nodeValue = after.nodeValue.substring(regs[0].length); | |
node.parentNode.insertBefore(match, after); | |
} | |
function textNodesUnder(el){ | |
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false); | |
while(n=walk.nextNode()) a.push(n); | |
return a; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment