0
<!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');

user2243528
  • 425
  • 1
  • 3
  • 9

4 Answers4

1

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')
Christoph
  • 50,121
  • 21
  • 99
  • 128
1

$( '#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");
}
zdyn
  • 2,155
  • 1
  • 15
  • 17
0

Use the .length member to see if it exists.

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

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.