Saturday, August 24, 2013

Adding a custom Jquery function to check whether a element exists in a html page or not using Jquery

Please add the below code your custom .JS file

(function($) {
    if (!$.exist) {
        $.extend({
            exist: function(elm) {
                if (typeof elm == null) return false;
                if (typeof elm != "object") elm = $(elm);
                return elm.length ? true : false;
            }
        });
        $.fn.extend({
            exist: function() {
                return $.exist($(this));
            }
        });
    }
})(jQuery);

Usage
------------
// With ID
$.exist("#eleID");
// OR
$("#eleID").exist();

// With class name
$.exist(".class-name");
// OR
$(".class-name").exist();

// With just a tag // Probably not best idea as there will be other tags on the site
$.exist("div");
// OR
$("div").exist();

No comments:

Post a Comment