Checking If An Element Exists In jQuery

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) {
}

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
12 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.