user2243528
user2243528

Reputation: 435

issue with css selector in jquery

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
if ( $( '#nonexistent' ) ) { 
console.log('test');
}
</script>

Question:

Actually there is no such id #nonexistent in my page, but why this line still runs: console.log('test');

Upvotes: 0

Views: 73

Answers (4)

Christoph
Christoph

Reputation: 51211

Because $( '#nonexistent' ) returns an empty set (which is an basically an array) and empty arrays yield true in boolean context.

You need to check $('#nonexistent').length instead.

If you are interested about how this exactly works, read into this sitepoint article about truthy-/falsyness in javascript.

You could as well use

// pretty jQuery-like
document.querySelector('#nonexistent')
// or a bit faster faster:
document.getElementById('nonexistent')

Upvotes: 1

To test whether an element exists use the length function.

if ( $( '#nonexistent' ).length > 0) { console.log('test'); }

You don't need the > 0 but it helps with readability.

Upvotes: 0

user1908308
user1908308

Reputation:

Use the .length member to see if it exists.

if ( $( '#nonexistent' ).length ) { 
    console.log('test');
}

Upvotes: 0

zdyn
zdyn

Reputation: 2173

$( '#nonexistent' ) returns an object (jQuery object), and all objects have a truthiness of yes. You should instead use:

if ( $( '#nonexistent' )[0] ) { 
  console.log('test');
}

Or better yet, no need for jQuery at all:

if (document.getElementById("nonexistent")) {
  console.log("not gonna happen");
}

Upvotes: 1

Related Questions