Since you don't want to use a plugin, you could do this using replace()
:
$('span').html(function() {
return $(this).text().replace(searchString, '<div class="red">' + searchString + '</div>');
});
Just to note, nesting a div
within a span
is not valid. Also, the above example is case sensitive (ie. red
will not match the word Red
).
In order to remove the highlighting, you can use unwrap()
, targeting the div.red
that has been added:
$('div.red').contents().unwrap();