Check if jQuery selector exists

When you are using a jQuery plugin, sometimes you may need to add the code into an external javascript library that is loaded on every page. This can cause problems when you are using a document ready function and simply initiating a plugin on an object that does not exist on every page.

For example if we were to call jQuery masonry in an external javascript file we would probably do something like this:


When we move to another page that does not contain our class – masonry is still trigger. This unfortunately results in a javascript error – and rightly so! To fix this we need to do a quick check to see if our selector exists:

   var $selector = $('.myclass');
   if($selector.length){ // if this fails try $selector.length > 0 (greater than 0)

Just this little line of code will check to see if the selector is present before going ahead and attaching a plugin to it.