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 }
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


No Reader comments

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.