Why does $('#id') return true if id doesn't exist?
Posted
by David
on Stack Overflow
See other posts from Stack Overflow
or by David
Published on 2010-01-16T10:32:31Z
Indexed on
2010/03/24
4:23 UTC
Read the original article
Hit count: 252
jQuery
|JavaScript
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?
© Stack Overflow or respective owner