Skip to main content

Various examples of checking if a DOM element(s) exists.

/*The .length property in jQuery returns the length 
or number of elements inside an array or the string 
length. If you want to check the existence of the 
element, just check if the returned value of length 
is zero:*/

if (jQuery("#selector").length > 0) {
  alert('jQuery element found!');
}

// check if an element exists by using length
if ($("#selector").length) {
  alert('jQuery element found!');
}

// or length equals zero
if ($('element').length === 0) {
  alert('jQuery element NOT found!');
}

// ---------------------------------------------------------
// Without jQuery
// ---------------------------------------------------------

if (document.getElementById('elementID') !== null) {
  alert('DOM element found!');
}

if (document.getElementById('elementID')) {
  alert('DOM element found!');
}

// ------------------------------------------------------
// jQuery Exists Extension Function 
// ------------------------------------------------------

jQuery.fn.exists = function () {
  return jQuery(this).length > 0;
};

if (jQuery("#myselector").exists()) {
  alert('jQuery element found!');
}