Checking If An Element Exists In jQuery

3rd February 2013

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. if ($('.myelement').length > 0) {
  2.  
  3. }

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

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

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. if ($('.myelement').length == 0) {
  2.  
  3. }

Add new comment

The content of this field is kept private and will not be shown publicly.