toggleAttribute Flips Boolean Attributes
toggleAttribute flips boolean attributes with an optional force argument, unlike setAttribute which always writes a string value.
Code
// 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 —
documentwill 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.