jQuery Check if an Element Exists

Sam Deering

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 }

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.