1

Currently, I need to check a specific anchor tag to see if it contains certain text. If it does then I need it to change the text of another element. Just as an example, I have the following code. However, no matter what I put in as being contained within an anchor tag, it always alerts "yup!".

if ($("a:contains('Level 2 (Admin Only)')")) {
    alert("yup!");
} 
else {
    alert("nope!");
}

What am I doing wrong? Should I use a different selector method?

3 Answers 3

5

You have to check the size of the jQuery object. jQuery returns an object, consisting of all matched elements.

 // If .length == zero, it evaluates to false in an if condition
if ($("a:contains('Level 2 (Admin Only)')").length) {
Sign up to request clarification or add additional context in comments.

Comments

4

That is because $("a:contains('Level 2 (Admin Only)')") is always true.

Try this:

if($("a:contains('Level 2 (Admin Only)')").length) {
   alert("yup!");
}else{
   alert("nope!");
}

2 Comments

length != 0? Meh. This is JavaScript. Use the truthiness!
@MattBall just wanted to keep the if statement the same as the OP had it.
2

The jQuery method always returns an object whether the selector matched any elements or not; and objects are always truthy.

You should use the .length attribute instead, which will be truthy if an element was matched, and falsy if one wasn't.

if ($("a:contains('Level 2 (Admin Only)')").length) {
   alert("yup!");
}else{
   alert("nope!");
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.