Controllare se l'elemento esiste in jQuery

Come faccio a controllare se un elemento esiste se l'elemento è creato dal metodo .append()? $('elemId').length non funziona per me.

Soluzione

$('elemId').length non funziona per me.

Devi mettere # prima dell'id dell'elemento:

$('#elemId').length
---^

Con vanilla JavaScript, non c'è bisogno dell'hash (#), ad esempio document.getElementById('id_qui') , tuttavia quando si usa jQuery, è necessario mettere l'hash per indirizzare gli elementi basati su id proprio come i CSS.

Commentari (7)

Provate a controllare la lunghezza del selettore, se vi restituisce qualcosa allora l'elemento deve esistere altrimenti no.

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}
Commentari (4)

Se avete una classe sul vostro elemento, allora potete provare quanto segue:

if( $('.exists_content').hasClass('exists_content') ){
 //element available
}
Commentari (2)