JSFiddle - React, Tailwind, and code Playground

by hmdadou

HTML

<div>


Lorem ipsum dolor sit amet, tgdent Questions consectetur adipisicing elit. Ipsa sed Questions ratione dolorem at repellendus animi eveniet similique repellat, sequi rem tgdent numquam debitis sit reprehenderit laborum dicta omnis iure quidem atque?
</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(/tgdent/g, '<span class="foo">TG</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);
}