If one of two elements exists, do something

放肆的年华 提交于 2019-12-02 19:56:11
micahwittman
if ($(".element1").is('*') || $(".element2").is('*')) {
    // code
}

EDIT (per comment) Select elements by multiple classes in one call:

if ($(".element1, .element2").is('*')) {
    // code
}
3zzy
if ( $('#myDiv')[0] ) { //do something }

..works best!

Found here.

Aaron

All jQuery elements have the .length property. You can just go:

if ($('img').length) // Implies: If this element exists..

http://jqueryfordesigners.com/element-exists/

!$.isEmptyObject($.find('#urId'))

this will return "true" if the element exists and False if not

cheers :)

Just use .each().

$(".element1").each(function(){
  //Do Something here
}

Simple...

SpYk3HH

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

$.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')
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!