JavaScript
Article
By Sam Deering

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)
--ADVERTISEMENT--

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 }
Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account