Is there an “exists” function for jQuery?

Table of Contents

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

 

How Lack of Rest Can Impact Your Finances Small Businesses Can Enhance File Management Following these Tips How Much Do Real Estate Agents Spend on Marketing? How to Engage Your Online Audience for Long-Lasting Success Why is Plagiarism Such a Big Deal? Resume Service Review: Why Everyone Should Use It
adbanner