jQuery Plugin for Checking the Existence of Elements

Posted in Javascript on March 3rd, 2011 – Tags: Be the first to comment

Sometime it’s really annoying to repeat some condition check to determines the existence of an element(s) in jQuery.

var foo = $ ('bar');
if (foo.length == 0)
    alert('bar NOT FOUND! ");


In short, jQuery selector—jQuery() or $()—always return an object even if the element did not exist. In the example below show you how to create element using jQuery selector.

//jQuery
var foo = $('<div id="bar">');
//Standard Javascript
var foo = document.createElement ('div');
foo.id = "bar";

Luckily, when the element(s) exist it will return the element-object as array, so we can check that with if/else condition we mentioned above. But it’s still annoying, because we want a shortcut way.

So here we create a plugin for our lazy-daze in daily Javascript programming. We call it found plugin — of course you can change it to whatever name you want.

(function ($) {
    $.extend($.fn, {
        found: function() {
            if (this.length == 0) return null;
            return this;
        }
    });
})(jQuery);

How we can use it? Here we go…

//now.. if 'bar' not found it will return null
var foo = $('bar').found();

Good luck and have a nice day!


Leave a Reply