Pregunta

Actualmente hago esto para verificar si existe uno de dos elementos:

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

¿Existe una mejor manera de reescribir lo mismo?Quiero decir, es .length lo mismo que .length > 0?

¿Fue útil?

Solución 2

if ( $('#myDiv')[0] ) { //do something }

.. funciona mejor!

Encontrados aquí .

Otros consejos

if ($(".element1").is('*') || $(".element2").is('*')) {
    // code
}

Editar (por comentario) Seleccionar elementos por múltiples clases en una llamada:

if ($(".element1, .element2").is('*')) {
    // code
}

Todos los elementos de jQuery tienen la propiedad .length. Que sólo puede ir:

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

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

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

esto devolverá "true" si el elemento existe y falso si no

aplausos :)

Sólo tiene que utilizar each ().

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

simple ...


Ver versión extremadamente actualizada de este complemento. aquí!Ahora utiliza la función de devolución de llamada para que pueda mantener la capacidad de encadenamiento si así lo desea.Puede reemplazar completamente si declaración o todavía se puede utilizar dentro si declaración


Podrías crear un complemento jQuery muy simple para esto, como tal:

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

USAR

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

Con tu declaración If

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

Por supuesto, este complemento podría ampliarse aún más para que sea mucho más sofisticado (manejar múltiples llamadas a la vez, crear elementos inexistentes basados ​​en un cochecito), pero tal como está ahora, realiza una función muy simple y muy necesaria...¿Existe este elemento?devolver True o False

jsFiddle

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

uso:

$('.element1, .element2').exists(function(els) {
    // this and els refers to $('.element1, .element2')
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top