Is there an “exists” function for jQuery?

  1. Home
  2. javascript
  3. Is there an “exists” function for jQuery?

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}

Is there a more elegant way to approach this? Perhaps a plugin or a function?

First answer

In JavaScript, everything is ‘truthy’ or ‘falsy’, and for numbers 0 (and NaN) means false, everything else true. So you could write:

if ($(selector).length)

You don’t need that >0 part.

Second answer

Yes!

jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}

This is in response to: Herding Code podcast with Jeff Atwood

Third answer

If you used

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

you would imply that chaining was possible when it is not.

This would be better:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

Alternatively, from the FAQ:

if ( $('#myDiv').length ) { /* Do something */ }

You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

if ( $('#myDiv')[0] ) { /* Do something */ }
Reprint:https://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
Spread the love

Related articles

Comments are closed.