If one of two elements exists, do something

前端 未结 7 1111
遇见更好的自我
遇见更好的自我 2021-02-02 05:21

I currently do this to check if one of two elements exists:

if ($(\".element1\").length > 0 || $(\".element2\").length > 0) {
  //do stuff...
}
         


        
7条回答
  •  半阙折子戏
    2021-02-02 06:14


    See Extremely updated version of this plugin here! Now uses callback function so you can maintain chainability if you choose. Can completely replace if statement or can still be used within if statement


    You could create a very simple jQuery plug-in for this, as such:

    jsFiddle

    (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);
    

    USE

    //  With ID 
    $.exist("#eleID");
    //  OR
    $("#eleID").exist();
    
    //  With class name
    $.exist(".class-name");
    //  OR
    $(".class-name").exist();
    
    //  With just tag // prolly not best idea aS there will be other tags on site
    $.exist("div");
    //  OR
    $("div").exist();
    

    With your If statement

    if ($(".element1").exist() || $(".element2").exist()) {
        ...stuff...
    }
    

    Of course this plugin could be further extended to be much more fancy (handling multiple calls at once, creating non-existing elements based on a pram), but as it stand now, it does a very simple, very needed function ... Does this element exist? return True or False

    jsFiddle

提交回复
热议问题