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.

2 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

Leave a Reply

Commenting Tips

  • These tags can be used (optional): <a href="" title="" rel=""> <abbr title=""> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strong> <pre>
  • When posting code, please use <code>your code here</code> or <pre><code>your code here</code></pre> for larger blocks.
    Escape < and > with &lt; and &gt;