Checking If An Element Exists In jQuery

Sunday, February 3, 2013 - 18:32

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.

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

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

1
2
3
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.

1
2
3
if ($('.myelement').length == 0) {
 
}
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment