If one of two elements exists, do something

前端 未结 7 859
遇见更好的自我
遇见更好的自我 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:09

    $.fn.exists = function(ifExists) {
        return this.length ? ifExists.call(this, this) : this;
    };
    

    usage:

    $('.element1, .element2').exists(function(els) {
        // this and els refers to $('.element1, .element2')
    });
    

提交回复
热议问题