Check if element exists in jQuery

To check if an item is present in the DOM using jQuery, it is sufficient to use the length property, like this:

if ($('#myElement').length) {
    // Exists
}
else {
    // Not Exists
}

Or you can create a small jQuery plugin

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

To use as follows:

if ($("#myElem").exists()){
    // Exists.
}

The .exists () function is present in our Javascript library: Sambuca JS.

Leave a Comment

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