<p id="text">Learn JS fast. A <b>js</b> quiz <script> is just text.</p>
Wrap every case-insensitive match of a search term in a <mark> element without using innerHTML on user data: walk the text nodes, split them and insert real elements. Print the resulting HTML and the number of matches.
Solution
main.js
function highlight(root, term) {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const textNodes = [];
while (walker.nextNode()) textNodes.push(walker.currentNode); // collect first: we change the tree below
const needle = term.toLowerCase();
let count = 0;
for (const node of textNodes) {
const text = node.data;
const parts = [];
let from = 0, at;
while ((at = text.toLowerCase().indexOf(needle, from)) !== -1) {
parts.push(text.slice(from, at));
parts.push(Object.assign(document.createElement("mark"), { textContent: text.slice(at, at + term.length) }));
from = at + term.length;
count++;
}
if (parts.length) node.replaceWith(...parts, text.slice(from));
}
return count;
}
const p = document.getElementById("text");
const matches = highlight(p, "js");
console.log(p.innerHTML);
console.log("matches:", matches);
Output Verified by running it on Node.js
Learn <mark>JS</mark> fast. A <b><mark>js</mark></b> quiz <script> is just text.
matches: 2
Strings passed to replaceWith become text nodes, so the page text is never parsed as HTML – the <script> stays harmless text. Matches inside nested elements (the b) are found too.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!