• support@answerspoint.com

Is there an “exists” function for jQuery?

2000

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?

  • jQuery

  • asked 9 years ago
  • B Butts

2Answer


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

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

There you go!

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

  • answered 8 years ago
  • Sandy Hook

0

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 */ }
  • answered 8 years ago
  • Gul Hafiz

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2000 times
  • active 9 years ago

Best Rated Questions