Reputation:
I am trying to at the moment simply alert if an element contains specific text string. Here is what I have so far -
<div class="first">This is the first div</div>
<div class="second">This is the second div</div>
if($(".first:contains('first')")){
alert("Found It!");
}
My problem is, it will alert the message regardless, I f I change it to a String that is not in any of the elements it will still output the alert.
Can anyone see where I am going wrong?
Thanks
Upvotes: 1
Views: 129
Reputation: 337701
Your condition is incorrect as the selector will always equate to true because it returns an object, not a boolean value.
Instead, check to see if the selector returned any elements by using length
:
if ($(".first:contains('first')").length){
alert("Found It!");
}
Upvotes: 3
Reputation: 4291
If you want to look for specific texts then use this:
if($(".first").text().indexOf("first")>0){
alert("Found It!");
}
Upvotes: 0