javascript tutorial - [Solved-5 Solutions] Exists function for jQuery - javascript - java script - javascript array



Problem:

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

The current code that we have is this:

if ($(selector).length > 0) {
    // Do something
}
click below button to copy the code. By JavaScript tutorial team

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

Solution 1:

In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false, everything else true. So we could write: if ($(selector).length) We don't need that >0 part.

Solution 2:

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

if ($(selector).exists()) {
    // Do something
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

If we used

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
click below button to copy the code. By JavaScript tutorial team
  • we 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)) { }
click below button to copy the code. By JavaScript tutorial team
if ( $('#myDiv').length ) { /* Do something */ }
click below button to copy the code. By JavaScript tutorial team

We 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 */ }
click below button to copy the code. By JavaScript tutorial team

Solution 4:

We can use this:

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

// if element does not exist
if(!$('selector').length){ /* do something */ }
click below button to copy the code. By JavaScript tutorial team

Solution 5:

We can save a few bytes by writing:

if ($(selector)[0]) { ... }
click below button to copy the code. By JavaScript tutorial team

This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.


Related Searches to javascript tutorial - Exists function for jQuery