How to tell if an element exists with jQuery
Posted April 10th, 2009 in Javascript
Last week I looked at how to get the total number of matched elements with jQuery which also showed how to tell if an element exists with jQuery. I've decided to create a second post just showing how to tell if an element exists to make it easier to find this functionality when searching this blog.
Using regular Javascript, you'd do this to tell if an element exists:
if(document.getElementById('example')) {
// do something
}
else {
// do something else
}
In jQuery you can do it like this instead, using the .length property:
if($('#example').length) {
// do something
}
else {
// do something else
}
Even better, if you wanted to work out if a type of tag existed within the div called #example you can easily do this with jQuery. For example, you could do this to tell if there are <img> tags within #example:
if($('#example img').length) {
// do something
}
else {
// do something else
}
Much easier than trying to work out how to do this with regular Javascript.
Related posts:
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Attaching an event to an element with jQuery (Tuesday, February 24th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)
- Loading content with jQuery AJAX and dealing with failures (Friday, February 6th 2009)
- Loading content with jQuery AJAX - selecting the element to inject (Sunday, January 18th 2009)

Comments
blog comments powered by Disqus