Question

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.

Was it helpful?

Solution

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) {
  // ...
}

OTHER TIPS

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.

A jQuery object that contains no DOM nodes.

You should be able to use

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

for your existence check.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top