1

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

2 Answers 2

3

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!");
}

Example fiddle

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to look for specific texts then use this:

if($(".first").text().indexOf("first")>0){
    alert("Found It!");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.