This answer works almost perfectly for my needs. The problem is that it will also match the URL values ββin the href attribute of the tag. So, if I have:
<a href="/a-link-to-a-porsche-page">This is a link to a porsche page</a>
and use this selector:
$("a").highlight("porsche", "highlighted");
porsche maps to both the URL and the link text. What can be done so that the values ββof the href attribute are omitted?
The previously mentioned answer for posterity:
jQuery.fn.highlight = function (str, className) { var regex = new RegExp(str, "gi"); return this.each(function () { this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";}); }); };
I do not know about jsfiddle. Here's a more complete example based on justkt's answer: http://jsfiddle.net/Dzejms/L5Knh/1/
source share