LearnFrenzy
Sign in Take a free test

DOM Manipulation · DOM Coding Problems · Question 9

Highlight a search term safely in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The page contains this HTML:

<p id="text">Learn JS fast. A <b>js</b> quiz &lt;script&gt; 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 &lt;script&gt; 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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links