Il metodo toggleAttribute()
dell'interfaccia Element
attiva/disattiva un attributo booleano (rimuovendolo se è presente e aggiungendolo se non è presente) sull'elemento specificato.
Sintassi
Element.toggleAttribute(name [, force]);
Parametri
name
- Una
DOMString
che specifica il nome dell'attributo da attivare. Il nome dell'attributo viene automaticamente convertito in minuscolo quandotoggleAttribute()
viene chiamato su un elemento HTML in un documento HTML. force
Optional- Un valore booleano per determinare se l'attributo deve essere aggiunto o rimosso, indipendentemente dal fatto che l'attributo sia presente o meno al momento.
Valore di ritorno
true
se l'attributo name
è eventualmente presente, in caso contrario false
.
Exceptions
InvalidCharacterError
- L'attributo specificato
name
contiene uno o più caratteri che non sono validi nei nomi degli attributi.
Esempio
Nell'esempio seguente, toggleAttribute()
viene utilizzato per commutare l'attributo readonly
di un <input>
.
HTML
<input value="text">
<button>toggleAttribute("readonly")</button>
JavaScript
var button = document.querySelector("button");
var input = document.querySelector("input");
button.addEventListener("click", function(){
input.toggleAttribute("readonly");
});
Risultato
DOM methods dealing with element's attributes:
Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with Attr nodes directly (seldom used) |
DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used) |
---|---|---|---|
setAttribute (DOM 1) |
setAttributeNS |
setAttributeNode |
setAttributeNodeNS |
getAttribute (DOM 1) |
getAttributeNS |
getAttributeNode |
getAttributeNodeNS |
hasAttribute (DOM 2) |
hasAttributeNS |
- | - |
removeAttribute (DOM 1) |
removeAttributeNS |
removeAttributeNode |
- |
Polyfill
if (!Element.prototype.toggleAttribute) {
Element.prototype.toggleAttribute = function(name, force) {
if(force !== void 0) force = !!force
if (this.getAttribute(name) !== null) {
if (force) return true;
this.removeAttribute(name);
return false;
} else {
if (force === false) return false;
this.setAttribute(name, "");
return true;
}
};
}
Specifiche
Specifica | Stato | Commento |
---|---|---|
DOM The definition of 'Element.toggleAttribute' in that specification. |
Living Standard |
Compatibilità con i browser
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.