Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery if "this" contains

I'm trying to change any elements containing a particular text string to a red color. In my example I can get the child elements to become blue, but there's something about the way I've written the 'Replace Me' line that is incorrect; the red color change doesn't happen. I note that the "contains" method is usually written as :contains but I couldn't get that to validate with $(this).

$('#main-content-panel .entry').each(function() {        $(this).css('color', 'blue');       });           $('#main-content-panel .entry').each(function() {    if($(this).contains("Replace Me").length > 0) {         $(this).css('color', 'red');      }       }); 

Fiddle: http://jsfiddle.net/zatHH/

like image 734
Chris Avatar asked Jan 24 '13 20:01

Chris


2 Answers

:contains is a selector. To check if a selector applies to given variable, you can use is:

if($(this).is(':contains("Replace Me")'))  

However Vega's solution is cleaner in this case.

like image 154
jkozera Avatar answered Sep 24 '22 00:09

jkozera


I don't think there is a .contains function in jQuery. There is a .contains function but that function is used to see if a DOM element is a descendant of another DOM element. See documentation for .contains. (Credits to @beezir)

I think you are looking for :contains selector. See below for more details,

$('#main-content-panel .entry:contains("Replace Me")').css('color', 'red'); 

http://jsfiddle.net/zatHH/1/

like image 20
Selvakumar Arumugam Avatar answered Sep 20 '22 00:09

Selvakumar Arumugam