Reputation: 19938
I am doing
var tag = $("#foo");
if(tag != null) {
// do something
}
the thing is, if even if the tag does not exist when the script is first executed, the value of tag variable is non-null and hence it breaks the code.
Why is it happening?
Upvotes: 2
Views: 2613
Reputation: 11028
you can also do the same thing by using size..
if ( $(selector).size() > 0 ) {
//do something
}
Upvotes: 0
Reputation: 6330
You would have to check the length
property to see if an element exists.
For a better way, you can refer to this Stackoverflow thread.
Upvotes: 0
Reputation: 138117
jQuery selectors never return null - you get an empty jQuery collection. You can test for:
if(tag.length){
// do something
}
tag.length
will be zero if nothing was found, which is a false value in JavaScript.
Even better, if all you do is simple jQuery operations you don't have to check the result at all - operations on an empty fail silently to allow chaining:
$('#id').show().find('.field').css('color', 'red')
.add('#otherId').text('done');
Upvotes: 8