JQuery Highlight words excluding href

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/

+4
source share
2 answers

One option is to expand the children of each object to make sure that you do not grab the DOM nodes in innerHTML.

Here is a pretty inefficient example that uses recursion for the children of each matching object:

 jQuery.fn.highlight = function (str, className) { var regex = new RegExp(str, "gi"); return this.each(function () { checkHighlight(this); }); function checkHighlight(obj) { var children = $(obj).children(); if(children.length == 0) { doHighlight(obj); } else { children.each(function() { checkHighlight(this); }); } } function doHighlight(obj) { obj.innerHTML = obj.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";}); } }; 

See in action here .

+2
source

------ ------ edit

a quick google search came up with this neat jquery plugin . the idea is the same as another answer, but it uses recursion and regular expression to make it more efficient. check it out.

+5
source

Source: https://habr.com/ru/post/1346604/


All Articles