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

前端 未结 6 702
野趣味
野趣味 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:50

    This behaviour was chosen because otherwise jQuery would regularly throw NullReference Exceptions

    Almost all jQuery functions return a jQuery object as a wrapper around the Dom elements in question, so you can use dot notation.

    $("#balloon").css({"color":"red"});
    

    Now imagine $("#balloon") returned null. That means that $("#balloon").css({"color":"red"}); would throw an error, rather than silently doing nothing as you would expect.

    Hence, you just gotta use .length or .size().

提交回复
热议问题