Skip to content

Instantly share code, notes, and snippets.

@FSou1
Created April 13, 2023 04:51
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 FSou1/c84ae03bdaa4128a97cb52aeb2dd1c9e to your computer and use it in GitHub Desktop.
Save FSou1/c84ae03bdaa4128a97cb52aeb2dd1c9e to your computer and use it in GitHub Desktop.
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