How to add underline to text that is viewed through contains ()

<div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn</div> <script> $("div:contains('John')").css("text-decoration", "underline"); </script> 

The above code will add an underline to the overall DIV that contains "John." But how can I do only "John" to emphasize. Please help me.

+4
source share
3 answers

You will have to wrap the text in the gap:

 $("div:contains('John')").each(function() { var $el = $(this); $el.html( $el.html().replace(/John/g, '<span style="text-decoration: underline">John</span>') ); }); 

http://jsfiddle.net/GP96T/2/

As @Brad Christie noted, you should only use this if you either know that you don't have “John” somewhere in your attributes, or that the div no children.

+6
source

Instead, you can:

 $oldcontent = $("div:contains('John')").html(); $("div:contains('John')").html($oldcontent.replace('John', '<u>John</u>'); 
+1
source

Hacked way:

 <div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn</div> <script> $("div:contains('John')").each(function(i,e){ var $this = $(this); var html = $this.html() .replace(/John/g,'<span style="text-decoration:underline;">John</span>'); $this.html(html); }); </script> 

As seen here

But be careful, if you have "John" in the link or title tag, this will also replace these instances. eg.

 <div><img src="..." title="This is John" /></div> 

becomes:

 <div><img src="..." title="This is <span style="text-decoration:underline;">John</span>" /></div> 

(undesirable if I thought)

-1
source

All Articles