jQuery fornisce il metodo .attr()
come un getter/setter per gli attributi HTML. Come setter si comporta come una più elaborata versione
del metodo setAttribute()
del DOM. I problemi cominciano quando questo metodo viene usato come getter.
Le specifiche DOM definiscono il metodo getAttribute()
per ogni
elemento HTML. Questo metodo restituisce il valore dell'attributo come stringa o una stringa vuota se l'attributo non esiste.
Inoltre le stesse specifiche definiscono il metodo hasAttribute()
che verifica se un elemento ha un dato attributo restituendo un valore booleano:
var element = document.getElementById('test');
if(!element.hasAttribute('title')) {
element.setAttribute('title', 'Test');
}
jQuery fornisce invece il solo metodo .attr()
. Questo metodo restituisce undefined
se un elemento non ha un dato attributo:
var noAttr = $('#test').attr('title');
if(typeof noAttr == 'undefined') {
$('#test').attr('title', 'Test');
}
Questo approccio tuttavia non è infallibile. Si raccomanda pertanto di utilizzare il più affidabile metodo del DOM:
(function($) {
if(typeof $.fn.hasAttr !== 'function') {
$.fn.hasAttr = function(attr) {
var $element = $(this),
element = $element[0];
if(!element.hasAttribute(attr)) {
return false;
}
return true;
};
}
})(jQuery);
Ho riassunto il comportamento di jQuery nella seguente pagina.