Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Element
  4. toggleAttribute()

Element: toggleAttribute() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨October 2018⁩.

ThetoggleAttribute() method of theElement interface toggles a Boolean attribute (removing it if it ispresent and adding it if it is not present) on the given element.

Syntax

js
toggleAttribute(name)toggleAttribute(name, force)

Parameters

name

A string specifying the name of the attribute to be toggled. Theattribute name is automatically converted to all lower-case whentoggleAttribute() is called on an HTML element in an HTML document.

forceOptional

A boolean value which has the following effects:

  • if not specified at all, thetoggleAttribute method "toggles" the attribute namedname — removing it if it is present, or else adding it if it is not present
  • if true, thetoggleAttribute method adds an attribute namedname
  • if false, thetoggleAttribute method removes the attribute namedname

Return value

true if attributename is eventuallypresent, andfalse otherwise.

Exceptions

InvalidCharacterErrorDOMException

The specified attributename contains one or more characters whichare not valid in attribute names.

Examples

In the following example,toggleAttribute() is used to toggle thedisabled attribute of an<input>.

HTML

html
<input value="text" /> <button>toggleAttribute("disabled")</button>

JavaScript

js
const button = document.querySelector("button");const input = document.querySelector("input");button.addEventListener("click", () => {  input.toggleAttribute("disabled");});

Result

Specifications

Specification
DOM
# ref-for-dom-element-toggleattribute①

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp