jQuery Check for Element Exists Examples
When using jQuery did you ever wonder how to check for element existence using a selector? In this article, I am going to show you how you can check if element exists or not on a page, using jQuery. You can use a selector or a class to find out if that related element exists or not. I am also going to show the right way and the wrong way for checking the element’s existence, such as a div. You can do all this with just 1 line of code. Read on to find out more.
How to Check for an Element to see if it Exists or Not using jQuery – Examples
Now there are two ways of checking if an element exists or not. One is a wrong way and the other is a correct way. Let me show you the wrong way to do this first so that you can avoid doing it in future:
Wrong Way:
if ($("#my_div"))
{
//Do your processing here
}Correct Way:
if ($("#my_div").length > 0){
{
//Do your processing here
}As you can see, jquery length function is very handy to check for element exists.
Your Turn!
Do you know of any other way to check if element exists or not using jQuery? Feel free to comment below.