Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 726
David Hellsing Avatar asked Jan 16 '10 10:01

David Hellsing


People also ask

What does $( function ()) short hand do?

It's just shorthand for $(document). ready() , as in: $(document). ready(function() { YOUR_CODE_HERE }); Sometimes you have to use it because your function is running before the DOM finishes loading.

What does $() mean in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

What does the $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

What does $() mean in HTML?

Usually when you encounter $() , that means the developer is using a javascript library, such as jQuery. The $ symbol is the namespace for those libraries. All the functions they define begin with $. , such as $.


1 Answers

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

like image 140
Dan Avatar answered Sep 20 '22 14:09

Dan