Sionide21
Sionide21

Reputation: 2211

jQuery: What is returned if $('#id') doesn't match anything?

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

Answers (4)

Sudhir Jonathan
Sudhir Jonathan

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

PepperBob
PepperBob

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

Ayman Hourieh
Ayman Hourieh

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

waxwing
waxwing

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

Related Questions