Why does $('#id') return true if id doesn't exist?

前端 未结 6 714
野趣味
野趣味 2020-11-28 13:08

I always wondered why jQuery returns true if I\'m trying to find elements by id selector that doesnt exist in the DOM structure.

Like this:

6条回答
  •  悲&欢浪女
    2020-11-28 13:51

    You could check the .length property of the jQuery object. Like this:

    if($("#two").length > 0) { // exists...
    
    } else { // doesn't exist
    
    }
    

提交回复
热议问题