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>');
});
Tags :

Related Posts

M.Muzammil

I am Muzammil, a Self-taught Web Designer & Developer. I haven't yet completed my college degree. Started learning programming at the age of 12 and still learning. I love to work in Javascript and make eye-catchy designs. Free for your calls :)

Be The First To Comment

Add Comment