Domanda

Come posso verificare l'esistenza di un elemento in jQuery?

Il codice attuale che ho è questo:

if ($(selector).length > 0) {
    // Do something
}

Esiste un modo più elegante per affrontare questo problema?Forse un plugin o una funzione?

È stato utile?

Soluzione

In JavaScript tutto è "vero" o "falso", anche per i numeri 0 (e NaN) significa false, tutto il resto true.Quindi potresti scrivere:

if ($(selector).length)

Non ne hai bisogno >0 parte.

Altri suggerimenti

SÌ!

jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}

Questo in risposta a: Podcast Herding Code con Jeff Atwood

Se hai usato

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

implicheresti che il concatenamento fosse possibile quando non lo è.

Sarebbe meglio:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

In alternativa, dalle domande frequenti:

if ( $('#myDiv').length ) { /* Do something */ }

Potresti anche usare quanto segue.Se non sono presenti valori nell'array di oggetti jQuery, ottenere il primo elemento nell'array restituirebbe unfine.

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

Puoi usare questo:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }

Il modo più veloce e semanticamente più autoesplicativo per verificare l'esistenza è in realtà utilizzare plain JavaScript:

if (document.getElementById('element_id')) {
    // Do something
}

È un po' più lungo da scrivere rispetto all'alternativa alla lunghezza jQuery, ma viene eseguito più velocemente poiché è un metodo JS nativo.

Ed è meglio dell'alternativa di scriverne uno tuo jQuery funzione.Questa alternativa è più lenta, per i motivi indicati da @snover.Ma darebbe anche ad altri programmatori l'impressione che il file exists() La funzione è qualcosa di inerente a jQuery. JavaScript sarebbe/dovrebbe essere compreso da altri che modificano il tuo codice, senza aumentare il debito di conoscenza.

NB: Notare la mancanza di un "#" prima di element_id (poiché questo è semplice JS, no jQuery).

Puoi risparmiare qualche byte scrivendo:

if ($(selector)[0]) { ... }

Funziona perché ogni oggetto jQuery si maschera anche da array, quindi possiamo utilizzare l'operatore di dereferenziazione dell'array per ottenere il primo elemento dal vettore.Ritorna undefined se non è presente alcun elemento nell'indice specificato.

Puoi usare:

if ($(selector).is('*')) {
  // Do something
}

UN poco più elegante, forse.

Questo plugin può essere utilizzato in un file if affermazione come if ($(ele).exist()) { /* DO WORK */ } o utilizzando una richiamata.

Collegare

;;(function($) {
    if (!$.exist) {
        $.extend({
            exist: function() {
                var ele, cbmExist, cbmNotExist;
                if (arguments.length) {
                    for (x in arguments) {
                        switch (typeof arguments[x]) {
                            case 'function':
                                if (typeof cbmExist == "undefined") cbmExist = arguments[x];
                                else cbmNotExist = arguments[x];
                                break;
                            case 'object':
                                if (arguments[x] instanceof jQuery) ele = arguments[x];
                                else {
                                    var obj = arguments[x];
                                    for (y in obj) {
                                        if (typeof obj[y] == 'function') {
                                            if (typeof cbmExist == "undefined") cbmExist = obj[y];
                                            else cbmNotExist = obj[y];
                                        }
                                        if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
                                        if (typeof obj[y] == 'string') ele = $(obj[y]);
                                    }
                                }
                                break;
                            case 'string':
                                ele = $(arguments[x]);
                                break;
                        }
                    }
                }

                if (typeof cbmExist == 'function') {
                    var exist =  ele.length > 0 ? true : false;
                    if (exist) {
                        return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
                    }
                    else if (typeof cbmNotExist == 'function') {
                        cbmNotExist.apply(ele, [exist, ele]);
                        return ele;
                    }
                    else {
                        if (ele.length <= 1) return ele.length > 0 ? true : false;
                        else return ele.length;
                    }
                }
                else {
                    if (ele.length <= 1) return ele.length > 0 ? true : false;
                    else return ele.length;
                }

                return false;
            }
        });
        $.fn.extend({
            exist: function() {
                var args = [$(this)];
                if (arguments.length) for (x in arguments) args.push(arguments[x]);
                return $.exist.apply($, args);
            }
        });
    }
})(jQuery);

jsFiddle

È possibile specificare uno o due callback.Il primo si attiverà se l'elemento esiste, il secondo si attiverà se l'elemento esiste non esistere.Tuttavia, se scegli di passare solo una funzione, verrà attivata solo quando l'elemento esiste.Pertanto, la catena morirà se lo fa l'elemento selezionato non esistere.Naturalmente, se esiste, verrà attivata la prima funzione e la catena continuerà.

Tieni presente che utilizzando il file la variante di callback aiuta a mantenere la concatenabilità – l'elemento viene restituito e puoi continuare a concatenare i comandi come con qualsiasi altro metodo jQuery!

Usi di esempio

if ($.exist('#eleID')) {    /*    DO WORK    */ }        //    param as STRING
if ($.exist($('#eleID'))) { /*    DO WORK    */ }        //    param as jQuery OBJECT
if ($('#eleID').exist()) {  /*    DO WORK    */ }        //    enduced on jQuery OBJECT

$.exist('#eleID', function() {            //    param is STRING && CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element EXIST    */
}, function() {            //    param is STRING && CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element DOES NOT EXIST    */
})

$('#eleID').exist(function() {            //    enduced on jQuery OBJECT with CALLBACK METHOD
    /*    DO WORK    */
    /*    This will ONLY fire if the element EXIST    */
})

$.exist({                        //    param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
    element: '#eleID',
    callback: function() {
        /*    DO WORK    */
        /*    This will ONLY fire if the element EXIST    */
    }
})

Vedo che la maggior parte delle risposte qui sono non preciso come dovrebbero essere, controllano la lunghezza dell'elemento, può essere OK in molti casi, ma non al 100%, immagina se invece il numero passasse alla funzione, quindi prototipo una funzione che controlla tutte le condizioni e restituisce la risposta come dovrebbe essere:

$.fn.exists = $.fn.exists || function() { 
  return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
}

Questo controllerà sia la lunghezza che il tipo, ora puoi controllarlo in questo modo:

$(1980).exists(); //return false
$([1,2,3]).exists(); //return false
$({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
$([{nodeName: 'foo'}]).exists() // returns false
$('div').exists(); //return true
$('.header').exists(); //return true
$(document).exists(); //return true
$('body').exists(); //return true

Non c'è davvero bisogno di jQuery.Con JavaScript semplice è più semplice e semanticamente corretto verificare:

if(document.getElementById("myElement")) {
    //Do something...
}

Se per qualsiasi motivo non desideri inserire un ID nell'elemento, puoi comunque utilizzare qualsiasi altro metodo JavaScript progettato per accedere al DOM.

jQuery è davvero interessante, ma non lasciare che il puro JavaScript cada nell'oblio...

Potresti usare questo:

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something*/}

Il motivo per cui tutte le risposte precedenti richiedono il file .length Il parametro è che utilizzano principalmente jquery $() selector che ha querySelectorAll dietro le quinte (o lo stanno usando direttamente).Questo metodo è piuttosto lento perché necessita di analizzare l'intero albero DOM cercando Tutto corrisponde a quel selettore e popola un array con essi.

Il parametro ['length'] non è necessario né utile e il codice sarà molto più veloce se lo utilizzi direttamente document.querySelector(selector) invece, perché restituisce il primo elemento che corrisponde o null se non trovato.

function elementIfExists(selector){  //named this way on purpose, see below
    return document.querySelector(selector);
}
/* usage: */
var myelement = elementIfExists("#myid") || myfallbackelement;

Tuttavia questo metodo ci lascia con l'oggetto reale restituito;il che va bene se non verrà salvato come variabile e utilizzato ripetutamente (mantenendo così il riferimento se lo dimentichiamo).

var myel=elementIfExists("#myid");
// now we are using a reference to the element which will linger after removal
myel.getParentNode.removeChild(myel);
console.log(elementIfExists("#myid")); /* null */
console.log(myel); /* giant table lingering around detached from document */
myel=null; /* now it can be garbage collected */

In alcuni casi questo potrebbe essere desiderato.Può essere utilizzato in un ciclo for come questo:

/* locally scoped myel gets garbage collected even with the break; */
for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
    if (myel == myblacklistedel) break;

Se in realtà non hai bisogno dell'elemento e vuoi ottenere/memorizzare solo un vero/falso, non raddoppiarlo!!Funziona con le scarpe slacciate, quindi perché annodarle qui?

function elementExists(selector){
    return !!document.querySelector(selector);
}
/* usage: */
var hastables = elementExists("table");  /* will be true or false */
if (hastables){
    /* insert css style sheet for our pretty tables */
}
setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
                           alert("bad table layouts");},3000);

ho trovato if ($(selector).length) {} essere insufficiente.Interromperà silenziosamente la tua app quando selector è un oggetto vuoto {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [▼ Object              ] 1
//    ► __proto__: Object

Il mio unico suggerimento è di eseguire un controllo aggiuntivo {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

Sto ancora cercando una soluzione migliore perché questa è un po' pesante.

Modificare: AVVERTIMENTO! Questo non funziona in IE quando selector è una stringa.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE

È $.contains() ciò che vuoi?

jQuery.contains( container, contained )

IL $.contains() Il metodo restituisce true se l'elemento DOM fornito dal secondo argomento è un discendente dell'elemento DOM fornito dal primo argomento, sia esso un figlio diretto o annidato più profondamente.Altrimenti restituisce false.Sono supportati solo i nodi elemento;se il secondo argomento è un nodo di testo o di commento, $.contains() restituirà falso.

Nota:Il primo argomento deve essere un elemento DOM, non un oggetto jQuery o un semplice oggetto JavaScript.

Puoi verificare che l'elemento sia presente o meno utilizzando la lunghezza nello script Java.Se la lunghezza è maggiore di zero, l'elemento è presente se la lunghezza è zero, l'elemento non è presente

// These by Id
if( $('#elementid').length > 0){
  // Element is Present
}else{
  // Element is not Present
}

// These by Class
if( $('.elementClass').length > 0){
  // Element is Present
}else{
  // Element is not Present
}

Verifica dell'esistenza di un elemento è documentato chiaramente nel sito Web ufficiale di jQuery stesso!

Usa il .lunghezza Proprietà della collezione jQuery restituita dal selettore:

if ($("#myDiv").length) {
    $("#myDiv").show();
}

Tieni presente che non è sempre necessario verificare se un elemento esiste.Il seguente codice mostrerà l'elemento se esiste e non farà nulla (senza errori) se non lo fa:

$("#myDiv").show();

questo è molto simile a tutte le risposte, ma perché non usare il file ! operatore due volte in modo da poter ottenere un valore booleano:

jQuery.fn.exists = function(){return !!this.length};

if ($(selector).exists()) {
    // the element exists, now what?...
}
$(selector).length && //Do something

Prova a testare DOM elemento

if (!!$(selector)[0]) // do stuff

Ispirato da la risposta di hiway Mi è venuto in mente quanto segue:

$.fn.exists = function() {
    return $.contains( document.documentElement, this[0] );
}

jQuery.contiene prende due elementi DOM e controlla se il primo contiene il secondo.

Utilizzando document.documentElement poiché il primo argomento soddisfa la semantica di exists metodo quando vogliamo applicarlo esclusivamente per verificare l'esistenza di un elemento nel documento corrente.

Di seguito, ho messo insieme uno snippet di confronto jQuery.exists() contro il $(sel)[0] E $(sel).length approcci che ritornano entrambi truthy valori per $(4) Mentre $(4).exists() ritorna false.Nel contesto di verificarne l'esistenza di un elemento nel DOM questo sembra essere il risultato desiderato.

$.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
  var testFuncs = [
    function(jq) { return !!jq[0]; },
    function(jq) { return !!jq.length; },
    function(jq) { return jq.exists(); },
  ];
    
  var inputs = [
    ["$()",$()],
    ["$(4)",$(4)],
    ["$('#idoexist')",$('#idoexist')],
    ["$('#idontexist')",$('#idontexist')]
  ];
  
  for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
    input = inputs[i][1];
    tr = "<tr><td>" + inputs[i][0] + "</td><td>"
          + testFuncs[0](input) + "</td><td>"
          + testFuncs[1](input) + "</td><td>"
          + testFuncs[2](input) + "</td></tr>";
    $("table").append(tr);
  }
td { border: 1px solid black }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="idoexist">#idoexist</div>
<table style>
<tr>
  <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
</tr>
</table>
<script>
  
  $.fn.exists = function() {
    return $.contains(document.documentElement, this[0]); 
  }
  
</script>

Mi piace semplicemente usare Javascript Plain Vanilla per farlo.

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}

Non c'è bisogno di jQuery

if(document.querySelector('.a-class')) {
  // do something
}

Mi sono imbattuto in questa domanda e vorrei condividere uno snippet di codice che attualmente utilizzo:

$.fn.exists = function(callback) {
    var self = this;
    var wrapper = (function(){
            function notExists () {}

            notExists.prototype.otherwise = function(fallback){
                if (!self.length) {                    
                    fallback.call();
                }
            };

            return new notExists;
        })();

    if(self.length) {
        callback.call();    
    }

    return wrapper;
}

E ora posso scrivere codice come questo:

$("#elem").exists(function(){
    alert ("it exists");
}).otherwise(function(){
    alert ("it doesn't exist");
});

Potrebbe sembrare molto codice, ma se scritto in CoffeeScript è piuttosto piccolo:

$.fn.exists = (callback) ->
    exists = @length
    callback.call() if exists        
    new class
       otherwise: (fallback) ->            
            fallback.call() if not exists

Ho avuto un caso in cui volevo vedere se un oggetto esiste all'interno di un altro, quindi ho aggiunto qualcosa alla prima risposta per verificare la presenza di un selettore all'interno del selettore.

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};

Che ne dite di:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

È molto minimale e ti evita di dover racchiudere il selettore $() ogni volta.

Sto usando questo:

    $.fn.ifExists = function(fn) {
      if (this.length) {
        $(fn(this));
      }
    };
    $("#element").ifExists( 
      function($this){
        $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
      }
    ); 

Esegui la catena solo se esiste un elemento jQuery - http://jsfiddle.net/andres_314/vbNM3/2/

Ecco il mio preferito exist metodo in jQuery

$.fn.exist = function(callback) {
    return $(this).each(function () {
        var target = $(this);

        if (this.length > 0 && typeof callback === 'function') {
            callback.call(target);
        }
    });
};

e un'altra versione che supporta la richiamata quando il selettore non esiste

$.fn.exist = function(onExist, onNotExist) {
    return $(this).each(function() {
        var target = $(this);

        if (this.length > 0) {
            if (typeof onExist === 'function') {
                onExist.call(target);
            }
        } else {
            if (typeof onNotExist === 'function') {
                onNotExist.call(target);
            }
        }
    });
};

Esempio:

$('#foo .bar').exist(
    function () {
        // Stuff when '#foo .bar' exists
    },
    function () {
        // Stuff when '#foo .bar' does not exist
    }
);

$("selector") restituisce un oggetto che ha l' length proprietà.Se il selettore trova degli elementi, questi verranno inclusi nell'oggetto.Quindi se controlli la sua lunghezza puoi vedere se esistono elementi.In JavaScript 0 == false, quindi se non ottieni 0 il tuo codice verrà eseguito.

if($("selector").length){
   //code in the case
} 

Ecco l'esempio completo di diverse situazioni e il modo per verificare se l'elemento esiste utilizzando direttamente se il selettore jQuery può funzionare o meno perché restituisce array o elementi.

var a = null;

var b = []

var c = undefined ;

if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
// output: a doesn't exit

if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
// output: b exist

if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
// output: c doesn't exit

SOLUZIONE FINALE

if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
//output : xusyxxs doesnn't exist

if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist

Non è necessario verificare se è maggiore di 0 Piace $(selector).length > 0, $(selector).length è sufficiente ed è un modo elegante per verificare l'esistenza degli elementi.Non penso che valga la pena scrivere una funzione solo per questo, se vuoi fare più cose extra, sì.

if($(selector).length){
  // true if length is not 0
} else {
  // false if length is 0
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top