this should be red alone

Exclude children from functions using jquery

Using the code below:

<p>Red red red red <a href="http://www.google.com"> this should be red alone</a> red red</p> 

How can I change all “red” to “yellow” EXCLUDES those indicated in the “a” tag?

I'm so far away:

 $("p").html(function(i,event){ return event.replace(/(red)/g,'yellow'); }); 

... which changes everything to yellow. I assume that I need to add something to the if clause line by line:

 if (event.target.tagName === "a") {return false} 

But I tried dozens of things that I found on stackoverflow, without any consequences. Any ideas?

+6
source share
3 answers

You can iterate over text nodes with contents() . This will not have any effect on event listeners on internal elements using html() .

 $('p').contents().each(function() { if (this.nodeType === 3) { this.textContent = this.textContent.replace(/red/gi, function(match) { return match === 'Red' ? 'Yellow' : 'yellow' }); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Red red red red <a href="http://www.google.com">red</a> red red</p> 
+4
source

The dirty way, because it is too specific and will not work if there is a lot of <a> in <p> for example, but it works if there is only one <a> in <p> .

The best way is to find the correct regular expression.

 var aContent = $('p > a')[0].outerHTML; $('p').html(function(i,event) { var parts = event.split(aContent); for (var i, l = parts.length; i<l; i++) { parts[i] = parts[i].replace(/red/ig, 'yellow'); } return parts.join(aContent); }); 
 <p>Red red red red <a href="http://www.google.com">red</a> red red</p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
+1
source

I made another route: I isolated the child, replaced his place with random text, performed our replacement as usual, and then replaced this random string with our child code again.

 var para = $("p"); var child = para.children()[0]; var text = child.outerHTML; para.find(child).replaceWith("zzzz"); $(para).html(function(i,event){ return event.replace(/(red)/gi,'yellow'); }); $(para).html(function(i,event){ return event.replace("zzzz", text ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Red red red red <a href="http://www.google.com"> this should be red alone</a> red red</p> 
0
source

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


All Articles