--- title: Element.toggleAttribute() slug: Web/API/Element/toggleAttribute translation_of: Web/API/Element/toggleAttribute ---
{{APIRef("DOM")}}

Il metodo toggleAttribute() dell'interfaccia {{domxref("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 {{domxref("DOMString")}} che specifica il nome dell'attributo da attivare. Il nome dell'attributo viene automaticamente convertito in minuscolo quando toggleAttribute() viene chiamato su un elemento HTML in un documento HTML.
force {{optional_inline}}
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 {{HTMLElement("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

{{ EmbedLiveSample('Esempio', '300', '50') }}

{{DOMAttributeMethods}}

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
{{SpecName('DOM WHATWG', '#dom-element-toggleattribute', 'Element.toggleAttribute')}} {{Spec2('DOM WHATWG')}}  

Compatibilità con i browser

{{Compat("api.Element.toggleAttribute")}}