Is there an “exists” function for jQuery?

Explanation

Yes, there is a exists function for jQuery. It can be used as shown in the below statement :

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

you would imply that chaining was possible when it is not.

You can also write it as follow:

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

Also as :

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

 Also, you can do as the following line. When there is no values in the jQuery object array then getting the first item in the array would return undefined. 

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

 

Also read, What is the !! (not not) operator in JavaScript?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *