There are places need to check the element existence and need to perform the operations. In such places the below piece of code might useful. Since its best practice to verify the element existence before to proceed the operation.

When using jQuery (or any other JavaScript library for that matter), have you ever wondered how to test whether an element exists using a selector? Well, maybe you haven't, but I have - lots of times - so I thought I'd share how it's done here because it's not as simple as it seems.

The existence can be validated by the following ways.

By Elements Length

The obvious thing would simply be to wrap a selector in an if statement, right?

if ($("#mydiv")){
  // do something here

Well, wrong - that won't work! When you use a selector, jQuery will always return an object. Therefore the if statement will always be true and never be false. In the case of an element that does not exist on the page, jQuery will return an object with nothing in it - an empty object. And therein lies our solution.

With a jQuery selector we can also use the length property, which will return the size of the object. Do you see where I'm heading with this? That's right, lets just change our if statement to:

if ($("#mydiv").length > 0){
  // do something here

Now our code works because when jQuery returns an empty object, the length property will return zero and therefore the if statement will be false. Hurrah!

Extending function

Its possible to extend the jquery function to validate the element existence by the following way.

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

if ($(selector).exists()) {
    // Do something

Check with Wildcard

The below code also will work fine

if ($(selector).is('*')) {
  // Do something


Here is a picture of me: