tags:

views:

2906

answers:

4

I'm trying to check in jquery if a div contains some text, and then add a class if it does.

So I wrote something like this:

    if( $("#field > div.field-item").text().indexOf('someText') = 0) {
        $("#somediv").addClass("thisClass");
    }

I'm not getting this to work.

<div id="field"><div class="field-item">someText</div></div>

<div id="somediv"></div>

Is this incorrect?

Thanks.

+6  A: 

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}
Ayman Hourieh
syntax is a bit wrong, it should be :contains not .contains
TM
+1, excellent second point. Killing my answer....
karim79
@TM - Was a typo. Fixed. Thanks!
Ayman Hourieh
correct syntax is :contains and not .contains
duckyflip
Thank you very much. :)
+1  A: 

You might want to try the contains selector:

if ($("#field > div.field-item:contains('someText')").length) {
    $("#somediv").addClass("thisClass");
}

Also, as other mentioned, you must use == or === rather than =.

TM
A: 
if( $("#field > div.field-item").text().indexOf('someText') >= 0)

Some browsers will include whitespace, others won't. >= is appropriate here. Otherwise equality is double equals ==

Tracker1
A: 

Ayman is right but, you can use it like that as well :

if( $("#field > div.field-item").text().indexOf('someText') >= 0) {
        $("#somediv").addClass("thisClass");
    }
Canavar