jQuery.fn.highlight = function(str, className) { var regex = new RegExp(str, "gi"); return this.each(function() { $(this).contents().filter(function() { return this.nodeType == 3 && regex.test(this.nodeValue); }).replaceWith(function() { return (this.nodeValue || "").replace(regex, function(match) { return "<span class=\"" + className + "\">" + match + "</span>"; }); }); }); };
Penggunaan
Seleksi sebuah elemen lalu terapkan fungsi .highlight("teks", "nama-kelas")
:
$('p').highlight("lorem ipsum", "yellow");
Sumber: A Web Coding Blog - Highlight Words in Text with jQuery
Sumber https://www.dte.web.id/