开发者

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

开发者 https://www.devze.com 2023-02-01 07:35 出处:网络
I am doing var tag 开发者_StackOverflow= $(\"#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 varia

I am doing

var tag 开发者_StackOverflow= $("#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?


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


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消