JSFiddle - React, Tailwind, and code Playground

by Mi_Creativity

HTML

<div id="wrapper">
  this is test looking for the the word Questions.
  <br>
  <div id="test">
    <p>Lorem ipsum dolor Questions sit amet, <strong>consectetur</strong> adipisicing elit.</p>
    <p>Questions 1</p>
    <p>Questions 2</p>
    <p>Questions 3</p>
    <p>Questions 4</p>
  </div>
  <div>Lorem ipsum dolor sit amet, Questions consectetur adipisicing elit. Ipsa sed Questions ratione dolorem at repellendus animi eveniet similique repellat, sequi rem numquam debitis sit reprehenderit laborum dicta omnis iure quidem atque?</div>
</div>

CSS

.foo {color: white; background-color: green; padding: 5px;}

JavaScript

var elements = document.body.getElementsByTagName('*');;

for (var i = 0; i < elements.length; i++) {
  var element = elements[i];

  for (var j = 0; j < element.childNodes.length; j++) {
    var node = element.childNodes[j],
      par = node.parentElement;

    // as well as checking the nodeType as text, we make sure the 
    // parent element doesn't have the class foo, so that we only
    // wrap the keyword once, instead of beign in a loop to infinity
    if (node.nodeType === Node.TEXT_NODE && !par.classList.contains('foo')) {
      updateText(node, par);
    }
  }
}

function updateText(el, par) {
  var nv = el.nodeValue,
    txt = nv.replace(/Questions/g, '<span class="foo">Questions</span> ');

  // replace the whole old text node with the new modified one
  // and inject it as parent HTML
  par.innerHTML = par.innerHTML.replace(nv, txt);
}