length

JQuery Logo

Checking If An Element Exists In jQuery

3rd February 2013 - 2 minutes read time

To verify that an element exists in the DOM you just need to use the .length property of a jQuery lookup. If the element is there then the number of elements found will be greater than 0.

if ($('.myelement').length > 0) {
}

This can be shorted by implicitly checking for a positive value of length.

if ($('.myelement').length) {
}

This is useful if you want to check that an element doesn't exist before trying to add it to the DOM. This helps to stop duplicate elements being added, which can create issues.

if ($('.myelement').length == 0) {
}