Esiste una funzione "exists" per jQuery?

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

Il codice attuale che ho è questo

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

C'è un modo più elegante per avvicinarsi a questo? Forse un plugin o una funzione?

Sì!

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

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

Questo è in risposta a: Herding Code podcast con Jeff Atwood

Commentari (11)

Se hai usato

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

implicherebbe che il concatenamento è possibile quando non lo è.

Questo sarebbe meglio:

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

In alternativa, dalle FAQ:

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

Si potrebbe anche usare quanto segue. Se non ci sono valori nell'array di oggetti jQuery, allora ottenere il primo elemento dell'array restituirebbe undefined.

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

Si può usare:

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

Un poco più elegante, forse.

Commentari (5)