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.
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.
A jQuery object that contains no DOM nodes.
You should be able to use
var item = $('#item');
if (!item[0]){
...
}
for your existence check.
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) {
// ...
}
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.
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.