views:

377

answers:

4

What is returned if $('#id') doesn't match anything? I figured it would be null or false or something similar so I tried checking like so:

var item = $('#item');
if (!item){
    ...
}

But that didn't work.

+3  A: 

A jQuery object that contains no DOM nodes.

You should be able to use

var item = $('#item');
if (!item[0]){
    ...
}

for your existence check.

waxwing
+18  A: 

You can find how many elements were matched using:

$('selector').length

To check whether no elements were matched, use:

var item = $('#item');
if (item.length == 0) {
  // ...
}
Ayman Hourieh
Yep, this is the correct way. To answer the question, though, it returns an object/array of DOM elements that match. And the 'length' property can be used on any javascript object (array,string,etc...) to determine its length (num elements, num characters, etc...).
KyleFarris
just use if ( item.length )
redsquare
+1  A: 

An alias of the length attribute is the size() method. So you basically could also query:

$("selector").size()

to see how many elements are matched.

PepperBob
+1  A: 

While $('selector').length is great for finding out how many objects your selector matches, its actually completely unnecesary. The thing about jQuery is that all selector based functions use length internally, so you could just do $(selector).hide() (or whatever) and it takes no action for an empty set.

Sudhir Jonathan
That's usually correct, but once in a while you just need to check for an element's existence. Good point though, so +1 anyway, since you are correct for most cases.
Matthew Crumley