最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery return value of a non-existing id or class? - Stack Overflow

programmeradmin2浏览0评论

I need to check if an object has same id on DOM, because i am trying to create a modal window library,

the problem is in browsers console when i write

$("#anonexistingid");

it returns []

but in my code

if($("#"+id)!==[]){
        return;
    }

just does not work. What is the proper way of defining an empty array?(Because i think [] means empty array, maybe not i am not sure :D)

I need to check if an object has same id on DOM, because i am trying to create a modal window library,

the problem is in browsers console when i write

$("#anonexistingid");

it returns []

but in my code

if($("#"+id)!==[]){
        return;
    }

just does not work. What is the proper way of defining an empty array?(Because i think [] means empty array, maybe not i am not sure :D)

Share Improve this question edited Jul 2, 2011 at 19:44 user113716 323k64 gold badges453 silver badges441 bronze badges asked Jul 2, 2011 at 19:38 gkaykckgkaykck 2,36711 gold badges35 silver badges52 bronze badges 1
  • 1 In any case, two objects are only equal if they are identical (the same). Even [] == [] returns false. – Felix Kling Commented Jul 2, 2011 at 19:45
Add a ment  | 

4 Answers 4

Reset to default 9

JQuery always returns an object. you can check it's length to see if it's empty or not:

if($("#"+id).length !== 0){

}

[] is an empty array. To test if empty, try:

if($("#"+id).length) { 
     //Element is found
}

try this . it returns true if object is empty , else returns false

 jQuery.isEmptyObject({}) // true
 jQuery.isEmptyObject({ foo: "bar" }) // false

http://api.jquery./jQuery.isEmptyObject/

You could use the size() method.

   if($("#"+id).size() > 0){
        return;
    }

This method returns the number of matched elements by $.

Hope this helps. Cheers

发布评论

评论列表(0)

  1. 暂无评论