Check if Element Exists in JQuery

Sometimes we come across a situation where we want to find if element exists in jquery. how can we Check if element exists jQuery? there is no such function available in jQuery but there is a simple way to check it.

//element exists code goes here
alert("Element exists");
//element doesn't exist code goes here
alert("Element doesn't exist");

How did it work?? Reason is simple! jQuery will always provide you return object which has length property irrespective of it found element or not! If it doesn’t find element then the length will be 0 (zero) other wise it will be more than 0.

if length is greater than 0 means it’s true otherwise expression is evaluated as false. This is how you can check if element exists in jQuery with ease!

Add a Comment

Your email address will not be published. Required fields are marked *