How to Check element exists or not in jQuery

Have you ever thought that what will happen if you try to access an element using jQuery which does not exist in your DOM? For example, I am accessing "dvText" element in below code and that element does not exists in my DOM.

var obj = $("#dvText");

What will happen?

There could be 2 possibilities. Either an error will be thrown and rest of the code will not get executed OR Nothing will happen.

If you think that error will be thrown then you are wrong. In jQuery, you don't need to be worried about checking the existence of any element. If element does not exists, jQuery will do nothing.

See live Demo and Code

Then what is this post all about? As post title says "How to Check element exists or not in jQuery", where you are not worried about element existence as jQuery handles it quite well. Well, Let say there is some long code related to the element you want to execute and you are not sure that element exists or not. jQuery doesn't throw error but that doesn't mean that you don't check the existence. So it's always better to check the existence. So how do we check it? See below code

if ($('#dvText').length) {  
    // your code  

jQuery provides length property for every element which returns 0 if element doesn't exists else length of the element.

See live Demo and Code

Feel free to contact me for any help related to jQuery, I will gladly help you.

Responsive Menu
Add more content here...