views:

61

answers:

3

Hello all,

I am trying to see if a particular string appears in a div. I have tried but it doesn't return true or false which is what I thought contains did?

if($("#path"+i+"_status:contains('!=')")){

     alert($("#path"+i+"_status:contains('!=')"));

    //alerts - [object object]

     return true;

}

Here is my HTML:

<div class="status" id="path3_status">
<img height="21" align="absmiddle" src="images/valid.jpg">Text File (3000) = Source Table (3000)<img height="21" align="top" src="images/info.jpg" " id="img_path3">
<a onclick="clear_file('TI004OBAE', 'path3');" href="#">Clear</a>
</div>

What am I doing wrong. How can I find out if a div contains the string "!="?

Thanks all for any help

+2  A: 

What you are doing here $("#path"+i+"_status:contains('!=')") is selecting an element with that ID and that contains '!='.

You could do something like

if($("#path"+i+"_status:contains('!=')").length > 0)

or

if($("#path"+i+"_status").text().indexOf("!=") != -1)

This isn't tested but should give you the basic idea.

*Edit - see Jeff's answer for clarification on why the first example works.

t_scho
+2  A: 

Yes, contains is a jQuery selector. Selectors return jQuery object instances, which maintain an array of references to the matched DOM elements.

Check jQuery's length property to see whether a selector matched at least one element:

if ($("#path"+i+"_status:contains('!=')").length > 0) {
    alert("found a match");
}
Jeff Sternal
Thanks for the explanation Jeff. A quick question, does `contains` only look at text within elements and not html within elements?
Abs
My pleasure! Yes - `contains` only looks at text within elements, not the markup.
Jeff Sternal
Awesome, thanks Jeff.
Abs
A: 

It might just be easier to use the class instead of the ID:

 $('.status:contains("!=")').each(function(){
  alert( $(this).text() );
 })
fudgey
Though it's easier to just use the class, you should always use an id if one is available - for speed and efficiency. (Which definitely matter in contemporary browsers!)
Jeff Sternal