How to Check in Jquery if Element Exists
close
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 you take a look out jquery snippet to check if element exists will look something like this.
if ($('#yourElement').length > 0) { 
    // it exists 
}

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

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

// 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
$('div.test').exists(function() {
  this.append('<p>I exist!</p>');
});

I hope it helped !
Disqus Codes

No comments

Notifications

Disqus Logo