How to Check in Jquery if Element Exists

How to Check in Jquery if Element Exists

How to Check in Jquery if Element Exists

In jQuery, you can use the .length property to check if an element exists. If the element exists, the length property will return the total number of the matched elements.

If you take a look at the jquery snippet to check if an element exists, it will look something like this.

Let's consider your element has the id of my_element

if ($('#my_element').length > 0) { 
    // it exists 
}

In the above code, our jquery .length property will return true if the specified element is founded. The above snippet is enough to check if an element exists in jquery.

Here I am having a javascript plugin with a fancy function with a callback to check if the element exists or not.

Tiny jQuery Plugin to check element's existence:

// Tiny jQuery Plugin
$.fn.exists = function (callback) {
    var args = [].slice.call(arguments, 1);

    if (this.length) {
        callback.call(this, args);
    }

    return this;
};

This is a very short plugin and the usage of this plugin is as under.

// Usage
$('#my_element').exists(function() {
  this.append('<p>I exist!</p>');
});

No Comment

Help us improve this article by leaving your feedback below.
Add Comment