user855
user855

Reputation: 19938

$("#id") retuning non-null value even if a tag with such an id does not exist

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

Answers (3)

Vivek
Vivek

Reputation: 11028

you can also do the same thing by using size..

if ( $(selector).size() > 0 ) {  
  //do something  
 }

Upvotes: 0

RabidFire
RabidFire

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

Kobi
Kobi

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

Related Questions