captainrad
captainrad

Reputation: 3830

If-then statement in jQuery

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?

Upvotes: 1

Views: 13963

Answers (3)

Matt
Matt

Reputation: 75307

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

Upvotes: 2

Naftali
Naftali

Reputation: 146302

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

Upvotes: 4

Rob W
Rob W

Reputation: 348972

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) {

Upvotes: 5

Related Questions