in jQuery

Check to see if a element exists in jQuery

In raw javascript using when dynamic elements you need to check to see if the element exists before you perform a certain action to the element or you will get a element undefined error. This is no different in jQuery except it is done in a different way. In raw JavaScript you would check if a element exist by using document.getElementById.

Pure JavaScript To Check If Element Exists


if(document.getElementById('div')){
      //do stuff
}

JQuery Approach To Check If Element Exists

But in jQuery you would think it would just be:


if($('#div')){
      //do stuff
}

But this doesn’t work in jQuery as whenever you use a selector jQuery will always return an object therefore the if statement will always return true, even if the div doesn’t exist. To get round this problem you need to count how many of the objects jQuery can find. Like this:


if($('#div').length){
     //do stuff
}

Using the length command it will return how many of #div’s it can find and if this number is more than 0 then an element will exist therefore perform actions on the div. If there isn’t a #div then the if statement will return false and we will not perform any actions on a element that doesn’t exist.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email