49

I'm used to Prototypejs, where $$("selector") will return null if no elements were found. This is convenient because I can do

if ($$("selector")) {}

to check if an element is in the DOM.

However, in jQuery $(selector) will return [] if no element is found, so now I need to do:

if ( $(selector).length > 0 )

This makes code slightly harder to read.

My question: What's the best way of doing this? Should I extend the jQuery object with methods like .empty() and .any(), or are there built in functions to do this?

Update: This also applies to other selectors on jQuery which should, anyways, only return one result (like parent(), or closest())

micho
  • 2,196
  • 2
  • 21
  • 26

3 Answers3

47
$.fn.exists = function () {
    return this.length !== 0;
}

Used like:

$("#notAnElement").exists();
Baz1nga
  • 15,485
  • 3
  • 35
  • 61
23

Using length is the best way. You shouldn't use empty() or size() > 0 since that just adds another entry to the call stack.

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
12
if ( $(selector)[0] )

That'll do it.

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129