javascript - Is there an "exists" function for jQuery?

ID : 199

viewed : 164

Tags : javascriptjqueryjavascript

Top 5 Answer for javascript - Is there an "exists" function for jQuery?

vote vote


In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:

if ($(selector).length) 

You don't need that >0 part.

vote vote



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

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

vote vote


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 */ } 
vote vote


You can use this:

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

// if element does not exist if(!$('selector').length){ /* do something */ } 
vote vote


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).

Top 3 video Explaining javascript - Is there an "exists" function for jQuery?