JSFiddle - React, Tailwind, and code Playground

by Hastig Z

HTML

<h2>Highlighting Foo</h2>
<div class="foo">
  Some test text looking for foo and here's a reference to <a href="foo">foo</a>.
</div>

CSS

.highlighter {
  background-color: yellow!important;
}

JavaScript

var gSearchedFor = 'foo';
var elementsArray = ['h2','div','a']; // add to these (i couldnt figure out how to combine the all selector(*) with :contains)
var elementsArrayLength = elementsArray.length;
var loopCounter = 0;
$.each(elementsArray, function() {
	loopCounter++;
	var thisElement = this;
  // from https://stackoverflow.com/a/16090558/3377049
  $(""+thisElement+":contains('"+gSearchedFor+"')").each(function() {
  	var replaceWithThis = $(this).html().replace(gSearchedFor, "<span class='highlighter'>"+gSearchedFor+"</span>");
    $(this).html(replaceWithThis);
  })
  // now search for capitalized versions of search term
  if (elementsArrayLength === loopCounter) { 
  	// from https://stackoverflow.com/a/42294347/3377049
    gSearchedFor = gSearchedFor.substring(0,1).toUpperCase() + gSearchedFor.substring(1,gSearchedFor.length);
    $.each(elementsArray, function() {
      var thisElement = this;
      // from https://stackoverflow.com/a/16090558/3377049
      $(""+thisElement+":contains('"+gSearchedFor+"')").each(function() {
        var replaceWithThis = $(this).html().replace(gSearchedFor, "<span class='highlighter'>"+gSearchedFor+"</span>");
        $(this).html(replaceWithThis);
      })
    })
  }
})