jQuery Check if an Element Exists

Sam Deering
Tweet

jQuery code snippet to check whether a html element exists on the current web page. The easiest way i’ve found to do this is to check the length of an object to see if it exists in the DOM.

//check if an element exists by using length
if ($("#id").length) {
  //it does!
}

//or length equals zero
$('element').length == 0; // no element found

//or using plain javascript
document.getElementById('eid') != null)

Snazzy jQuery Function, Sir?

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

if ($(selector).exists()) {
    // Do something
}

Or to check a jQuery object array for presence:

if ( $('#myDiv')[0] ) { //do something }

Free JavaScript: Novice to Ninja Sample

Get a free 32-page chapter of JavaScript: Novice to Ninja and receive updates on exclusive offers from SitePoint.

No Reader comments