Reputation: 2211
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.
Upvotes: 24
Views: 10119
Reputation: 17526
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.
Upvotes: 7
Reputation: 707
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.
Upvotes: 1
Reputation: 137276
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) {
// ...
}
Upvotes: 51
Reputation: 18783
A jQuery object that contains no DOM nodes.
You should be able to use
var item = $('#item');
if (!item[0]){
...
}
for your existence check.
Upvotes: 5