Como posso verificar a existência de um elemento em jQuery?
O código actual que eu tenho é este:
if ($(selector).length > 0) {
// Do something
}
Há uma maneira mais elegante de abordar isto? Talvez um plugin ou uma função?
Sim!
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}
Isto é em resposta a: Podcast de código de pastoreio com Jeff Atwood.
Se você usou
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
você implicaria que o encadeamento era possível quando não é.
Isto seria melhor:
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
Alternativamente, da FAQ:
if ( $('#myDiv').length ) { /* Do something */ }
Você também poderia usar o seguinte. Se não houver valores na matriz de objetos jQuery, então obter o primeiro item na matriz retornaria indefinido.
if ( $('#myDiv')[0] ) { /* Do something */ }