JavaScript Element toggleAttribute() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.toggleAttribute() is an instance method that toggles a Boolean attribute — adding it when missing, removing it when present. Learn MDN’s disabled input demo, the optional force parameter, the boolean return value, comparison with setAttribute() and removeAttribute(), and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Returns

boolean

03

Args

name, force?

04

Action

Add / remove

05

Best for

Boolean attrs

06

Status

Baseline widely

Introduction

Many HTML attributes are boolean: their presence means “on” and their absence means “off” — for example disabled, hidden, checked, and readonly.

element.toggleAttribute(name) flips that presence in one call (MDN). You do not need a separate if (hasAttribute) remove else set branch for simple toggles.

💡
Beginner tip

The method returns true when the attribute is present after the call, and false when it is not (MDN). Use that return value to update UI labels or log state without a second hasAttribute() check.

This page is part of JavaScript Element. Pair with hasAttribute(), setAttribute(), and removeAttribute().

Understanding the toggleAttribute() Method

Calling el.toggleAttribute(name) adds or removes a Boolean attribute named name (MDN).

  • It is an instance method on Element.
  • name — attribute name to toggle (lower-cased on HTML elements in HTML documents) (MDN).
  • force (optional) — true forces add; false forces remove; omitted toggles (MDN).
  • Returns true if the attribute is present after the call; otherwise false (MDN).
  • Throws InvalidCharacterError for invalid attribute names (MDN).
  • Ideal for boolean attributes; for valued attributes prefer setAttribute(name, value).

📝 Syntax

General form of Element.toggleAttribute (MDN):

JavaScript
toggleAttribute(name)
toggleAttribute(name, force)

Parameters

ParameterTypeDescription
namestringAttribute name to toggle. Lower-cased on HTML elements in HTML documents (MDN).
forceboolean (optional)If true, add the attribute. If false, remove it. If omitted, toggle (MDN).

Return value

true if attribute name is eventually present; false otherwise (MDN).

Exceptions

InvalidCharacterErrorname is empty or contains invalid characters such as ASCII whitespace, NULL, /, =, or > (MDN).

Common patterns

JavaScript
const input = document.querySelector("input");

// Toggle presence (MDN)
input.toggleAttribute("disabled");

// Force on / off
input.toggleAttribute("disabled", true);  // always add
input.toggleAttribute("disabled", false); // always remove

// Use return value
const isDisabled = input.toggleAttribute("disabled");
console.log(isDisabled); // true if disabled is now present

⚡ Quick Reference

GoalCode
Toggle attributeel.toggleAttribute("disabled")
Force addel.toggleAttribute("hidden", true)
Force removeel.toggleAttribute("hidden", false)
Check after toggleconst on = el.toggleAttribute("open")
Existence onlyel.hasAttribute("disabled")
Valued attributeel.setAttribute("id", "x")

🔍 At a Glance

Four facts to remember about Element.toggleAttribute().

Returns
boolean

Present?

Default
toggle

Add / remove

force
true|false

Optional

Status
baseline

Oct 2018

📋 Attribute APIs compared

toggleAttribute()setAttribute()removeAttribute()hasAttribute()
ActionAdd or removeAlways set valueAlways removeCheck only
Returnstrue / falseundefinedundefinedtrue / false
Best forBoolean attributesNamed valuesClear attributeExistence test
Force modeforce paramN/AN/AN/A

Examples Gallery

Examples follow MDN Element.toggleAttribute() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

MDN’s classic disabled toggle on an input.

Example 1 — Toggle disabled (MDN)

Click a button to enable or disable an input with one method call.

JavaScript
const button = document.querySelector("button");
const input = document.querySelector("input");

button.addEventListener("click", () => {
  input.toggleAttribute("disabled");
});
Try It Yourself

How It Works

MDN: when the attribute is present it is removed; when absent it is added. Perfect for boolean attributes like disabled.

Example 2 — Force add or remove with force

Pass true or false when you want set/remove semantics.

JavaScript
const box = document.getElementById("box");

box.toggleAttribute("hidden", true);  // ensure hidden is present
console.log(box.hasAttribute("hidden")); // true

box.toggleAttribute("hidden", false); // ensure hidden is removed
console.log(box.hasAttribute("hidden")); // false
Try It Yourself

How It Works

MDN: force: true always adds; force: false always removes. Useful when UI state comes from a boolean variable.

📈 Practical Patterns

Return value, hidden, and safe name checks.

Example 3 — Use the boolean return value

Know the new state immediately after toggling.

JavaScript
const btn = document.getElementById("mute");
const status = document.getElementById("status");

btn.addEventListener("click", () => {
  const muted = btn.toggleAttribute("aria-pressed");
  // aria-pressed is present when muted === true
  status.textContent = muted ? "Muted" : "Unmuted";
});
Try It Yourself

How It Works

MDN returns whether the attribute is present after the call. You can drive labels and styles from that boolean without calling hasAttribute() again.

Example 4 — Toggle hidden on a panel

Show or hide content using the native hidden attribute.

JavaScript
const panel = document.getElementById("panel");
const toggle = document.getElementById("toggle");

toggle.addEventListener("click", () => {
  const isHidden = panel.toggleAttribute("hidden");
  toggle.textContent = isHidden ? "Show panel" : "Hide panel";
});
Try It Yourself

How It Works

The HTML hidden attribute hides the element via the browser’s default stylesheet. Toggling it is a clean alternative to class-based show/hide for simple panels.

Example 5 — Guard invalid attribute names

Invalid names throw InvalidCharacterError (MDN).

JavaScript
const el = document.createElement("div");

try {
  el.toggleAttribute("ok-name");
  console.log("ok-name toggled");
  el.toggleAttribute("bad name"); // space is invalid (MDN)
} catch (err) {
  console.log(err.name); // InvalidCharacterError
}
Try It Yourself

How It Works

MDN: names must have at least one character and may not contain ASCII whitespace, NULL, /, =, or >.

🚀 Common Use Cases

  • Enable / disable form controls with disabled (MDN demo).
  • Show / hide panels with the hidden attribute.
  • Toggle ARIA boolean-style flags such as aria-expanded presence patterns.
  • Force attribute state from a boolean variable with force.
  • Replace verbose if (has) remove else set branches for boolean attrs.
  • Drive UI labels from the method’s boolean return value.

🧠 How toggleAttribute() Flips Presence

1

Receive name (and optional force)

el.toggleAttribute(name, force?) — name lower-cased on HTML elements (MDN).

Input
2

Decide add or remove

Toggle by default; force true adds; force false removes (MDN).

Decide
3

Update the attribute list

Attribute is inserted or deleted on the element.

Mutate
4

Return final presence

true if present after the call; false if absent (MDN).

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available, October 2018).
  • Designed for Boolean attributes; for valued attributes use setAttribute().
  • HTML attribute names are lower-cased automatically in HTML documents (MDN).
  • Invalid names throw InvalidCharacterError (MDN).
  • Related: hasAttribute(), setAttribute(), removeAttribute(), JavaScript hub.

Browser Support

Element.toggleAttribute() is Baseline Widely available (MDN: across browsers since October 2018). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.toggleAttribute()

Toggle Boolean attributes — add if missing, remove if present.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported — use set/removeAttribute polyfill
No
toggleAttribute() Excellent

Bottom line: Use toggleAttribute() for disabled, hidden, and other Boolean attributes. Pass force when you need explicit add or remove. Prefer setAttribute() when you need a value string.

Conclusion

Element.toggleAttribute() is the clean way to flip Boolean attributes. Use the optional force parameter for explicit add/remove, and the boolean return value to know the final state.

Continue with hasAttribute(), setAttribute(), removeAttribute(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use for Boolean attributes like disabled and hidden
  • Use the return value to update UI state
  • Pass force when syncing from a boolean variable
  • Prefer lower-case attribute names in HTML
  • Validate dynamic names before calling (MDN)

❌ Don’t

  • Use it when you need to set a string value (use setAttribute)
  • Pass names with spaces or = characters
  • Assume IE supports it without a polyfill
  • Toggle valued attributes if you care about preserving values
  • Ignore the return value when you need the new state

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.toggleAttribute()

One call to flip Boolean attribute presence.

5
Core concepts
🔁 02

Default

toggle

Flip
⚙️ 03

force

add/remove

Optional
04

Best for

boolean attrs

disabled
🌐 05

Support

baseline

Oct 2018

❓ Frequently Asked Questions

It toggles a Boolean attribute on the element: removes it if present, or adds it if not present (MDN).
No. MDN marks Element.toggleAttribute() as Baseline Widely available (across browsers since October 2018). It is not Deprecated, Experimental, or Non-standard.
true if the attribute is eventually present after the call, and false otherwise (MDN).
Optional boolean. If true, the attribute is added. If false, it is removed. If omitted, the attribute is toggled (MDN).
toggleAttribute() flips presence in one call and returns whether the attribute is present. setAttribute() always sets a value; removeAttribute() always removes. Use force true/false when you need set or remove semantics with the same API.
On an HTML element in an HTML document, the name is automatically converted to lower-case (MDN).
Did you know?

toggleAttribute() is to Boolean attributes what classList.toggle() is to CSS classes — one call flips state and gives you a boolean back. MDN’s demo uses it to enable and disable an <input> without juggling setAttribute / removeAttribute.

Next: scroll()

Continue the Element methods series with programmatic scrolling.

scroll() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful