Is there an “exists” function for jQuery?

0 votes
asked Aug 27, 2008 by jake-mcgraw

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 is a more elegant way to approach this? Perhaps a plugin or a function?

24 Answers

0 votes
answered Jan 17, 2008 by devon

You can use:

if ($(selector).is('*')) {
  // Do something
}

A little more elegant, perhaps.

0 votes
answered Aug 27, 2008 by jake-mcgraw

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

0 votes
answered Aug 14, 2009 by jon-erickson

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 */ }
0 votes
answered Jan 3, 2011 by yanni

You can use this:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }
0 votes
answered Jan 14, 2011 by amypellegrini

There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:

if(document.getElementById("myElement")) {
    //Do something...
}

If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.

jQuery is really cool, but don't let pure JavaScript fall into oblivion...

0 votes
answered Jan 1, 2012 by andy-314

I'm using this:

    $.fn.ifExists = function(fn) {
      if (this.length) {
        $(fn(this));
      }
    };
    $("#element").ifExists( 
      function($this){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
      }
    ); 

Execute the chain only if a jQuery element exist - http://jsfiddle.net/andres_314/vbNM3/2/

0 votes
answered Jan 5, 2012 by jcreamer898

I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};
0 votes
answered Jan 6, 2012 by oleg

I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [▼ Object              ] 1
//    ► __proto__: Object

My only suggestion is to perform an additional check for {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

I'm still looking for a better solution though as this one is a bit heavy.

Edit: WARNING! This doesn't work in IE when selector is a string.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
0 votes
answered Jan 11, 2012 by magne

The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:

if (document.getElementById('element_id')) {
    // Do something
}

It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.

And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.

NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).

0 votes
answered Jan 28, 2012 by sjg
$(selector).length && //Do something
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...