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

3
  • Check $('#nonexistent').length ? Commented Jun 19, 2013 at 7:50
  • If you want to check if an element exists you need to use length Commented Jun 19, 2013 at 7:50
  • stackoverflow.com/questions/3086068/… Check this Commented Jun 19, 2013 at 7:52

4 Answers 4

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')
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Use the .length member to see if it exists.

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

Comments

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.

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.