Home / How to tell if an element exists with jQuery

How to tell if an element exists with jQuery

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.