jQuery non dispone in modo nativo di un metodo simile a hasAttribute()
per stabilire se un elemento ha un dato attributo o meno. Tuttavia, possiamo usare il metodo attr()
per verificare la presenza di un attributo sull'elemento selezionato. Infatti questo metodo restituisce un valore booleano quando viene usato in costrutti condizionali.
Possiamo estendere jQuery con il metodo hasAttr()
:
(function($) {
$.fn.hasAttr = function(attr) {
attr = attr || 'class';
var that = this;
if(!that.attr(attr)) {
return false;
}
return true;
};
})(jQuery);
In questo caso, come per attr()
, non รจ necessario restituire this
. Vediamo un esempio:
<p id="one">Test</p>
<p>Test</p>
<p title="two">Test</p>
Eseguiamo il seguente test:
$(function() {
$('p').each(function() {
var $p = $(this);
console.log($p.hasAttr('id'));
console.log($p.hasAttr('title'));
});
});
che restituisce il seguente risultato:
true false false false false true