Check if html element exists in jQuery
Have you ever wondered how to check if the HTML element exists in jquery? Here are 3 ways with different selectors to do it.
Because if an element does not exist then jQuery will return an empty object and not NULL. So we can not be using the following way:
if ($("#myElement")){ | |
alert('myElement eixts!'); | |
}
|
We can use the length property with a jQuery selector if the length, not zero then the element exists.
Use id as jQuery selector
if ($("#myElement").length > 0){ | |
alert('myElement eixts!'); | |
}
|
Use CSS class name as jQuery selector
It will check to see if there any element exist with the specified class name.
if ($(".className").length > 0){ | |
alert('At least one element with given class className eixts!'); | |
}
|
Use element type as jQuery selector
if ($(":input").length > 0){ | |
alert('At least one input eixts!'); | |
}
|

Post a Comment