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 = [], 1);

  if (this.length) {, 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 !

Post a Comment

Help us improve this article by leaving your feedback below.
Previous Post Next Post