00 Votes

jQuery: Does an element exist?

Tip by Progger99 | 2013-01-28 at 20:47

Sometimes, we want to use jQuery to check whether there is an element existing in the current page. For example, to load an element only if it is not already present.

We are working with the length property:

if ($('#a').length == 0) {
  alert('The element with the ID a does not exist.');

if ($('#b').length > 0) {
  alert('The element with the ID a exists.');

The trick: jQuery stores all elements in an array. Having any selector, we can retrieve the length of this array with its property "length". Whenever the length is 0, we know that there are no items for this selector, so the requested element is not existing.

In the example, we can use any jQuery selector you can imagine. Therefore, we can test, for example, for the presence of groups, classes or images by simply using the appropriate selector:

if ($('.class').length > 0) {
  alert('Elements of the class "class" are not existing.');

if ($('img').length > 0) {
  alert('There are no images on this page.');

if ($('#a.b').length > 0) {
  alert('Element with the ID a has assigned class b.');

In this example, we test, whether there are elements on the website with the class "class" or whether there are images. We also check if there is an element with the ID "a", which has the class "b" assigned. As you can see: It's possible to use all typical jQuery selectors.

00 Votes

If you would like to have it more even simpler, just omit the "> 0":

if ($('#b').length) {
  alert('The element with the ID a exists.');

It is also working in this way, because the condition returns "false" at a length of 0 and "true" at a length greater 0.
2013-09-10 at 13:56

ReplyPositive Negative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

jQuery: Replace element

Question | 1 Answer

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.