JavaScript
Article

jQuery Check if an Element Exists

By 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 }

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.