Check if Element Exists with jQuery

I often forget the simplest programming stuff. How to check whether an element exists or not with jQuery is such a frequently recurring forgetful thing. Putting the code in an article might help, so here we go:

if( $('#elementID').length ) { // Exists...do something }

As you see the length property of the jQuery object is the key. If it’s not 0 the element exists.

3 Responses

  1. Mattias says:

    Or, to have it as a helper function:

    jQuery.fn.exists = function() { 
       return this.length > 0; 
    };

    And then use it like this:

    
    if ( $('#element').exists() ) { 
       // Do something
    }
  2. Ricky says:

    Mattias, martins fix is way better, no functions need to be parsed

  3. Gina says:

    Good points all around. Truly apidtcpaeer.