Is there an “exists” function for jQuery?

Solution:

JavaScript allows you to specify whether everything is true or false. Numbers 0 and 1 are false. You could also write:

if ($(selector).length)

This >0 part is not necessary.

Yes

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

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

This is in response the: Herding Code podcast featuring Jeff Atwood.

If you use

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

It would be easy to assume that chaining is possible, but it isn’t.

This would be even better.

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

Alternativ, you can also visit the FAQ:

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

The following could be used. If the jQuery object array does not contain any values, the first item would be returned undefined.

if ( $('#myDiv')[0] ) { /* Do something */ }

 

Exit mobile version