DOM Element.toggleAttribute() Method
The toggleAttribute() method adds a boolean attribute if it's missing or removes it if it's present.
Description
The toggleAttribute() method toggles a boolean attribute: it adds the attribute (with an empty value) if absent, and removes it if present. The force argument turns it into a one-way set or remove, which is handy when the state comes from a condition.
It's particularly convenient for attributes that work on presence alone, such as hidden, disabled, open, inert and required. When adding, the attribute gets an empty value; if it already had a value, toggling it off removes that value too.
Many of these attributes also have boolean properties, so el.hidden = !el.hidden does the same job as el.toggleAttribute('hidden'). Use whichever reads more clearly in your code.
Syntax
element.toggleAttribute(name)
element.toggleAttribute(name, force)Parameters
- nameThe name of the attribute.
- forceOptional.
trueto always add it,falseto always remove it.
Return Value
true if the attribute is present afterwards, otherwise false.
Example
Browser Support
The following information will show you the current browser support for the Element.toggleAttribute() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





