toggleAttribute Flips Boolean Attributes

toggleAttribute flips boolean attributes with an optional force argument, unlike setAttribute which always writes a string value.

JavascriptForm Validation

Code

javascriptsnippet
19 lines
// Boolean-ish attributes: presence means on, absence means off
const input = document.querySelector('#terms');

// Without force, toggleAttribute flips the current state
input.toggleAttribute('checked');
console.log('has checked:', input.hasAttribute('checked'));

input.toggleAttribute('checked');
console.log('after flip:', input.hasAttribute('checked'));

// A force argument pins the outcome no matter what the state was
input.toggleAttribute('disabled', true);
input.toggleAttribute('disabled', true);
console.log('disabled set twice:', input.hasAttribute('disabled'));

// setAttribute always writes a string value; removeAttribute drops the node
input.setAttribute('aria-label', 'Accept terms');
input.removeAttribute('aria-label');
console.log('aria removed:', input.hasAttribute('aria-label'));

How the snippet works

The file’s state is a handful of top-level bindings: input.

Caveats

  • Everything it calls is documented as part of the language core.
  • This is browser-side code — document will not resolve in Node.

Using it

Look for the has checked:, after flip:, disabled set twice: prefixes when the file runs; they tie each line to its step.

The key statements that remain

input.setAttribute('aria-label', 'Accept terms');
const input = document.querySelector('#terms');
input.toggleAttribute('disabled', true);

Interactive Tools for This Topic

FAQ

Does toggleAttribute Flips Boolean Attributes run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.