Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

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

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:

<div id="one">one</div>

<script>
    console.log( !!$('#one') ) // prints true
    console.log( !!$('#two') ) // is also true! (empty jQuery object)
    console.log( !!document.getElementById('two') ) // prints false
</script>

I know I can use !!$('#two').length since length === 0 if the object is empty, but it seems logical to me that a selector would return the element if found, otherwise null (like the native document.getElementById does).

F.ex, this logic can't be done in jQuery:

var div = $('#two') || $('<div id="two"></div>');

Wouldnt it be more logical if the ID selector returned null if not found?

anyone?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...