2

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?

user855
  • 19,048
  • 38
  • 98
  • 162

3 Answers3

8

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');
Kobi
  • 135,331
  • 41
  • 252
  • 292
0

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.

Community
  • 1
  • 1
RabidFire
  • 6,280
  • 1
  • 28
  • 24
0

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

if ( $(selector).size() > 0 ) {  
  //do something  
 }
Vivek
  • 10,978
  • 14
  • 48
  • 66