freecoding.school100% FREE · NO SIGNUP
The Old NetISSUE #42 of 60

setAttribute · getAttribute · removeAttribute

Pixel PeteVSQuirks Mode
Pixel Pete saysgetAttribute/setAttribute/removeAttribute read and write any HTML attribute.

setAttribute("aria-label", "x"), getAttribute, removeAttribute, and hasAttribute handle any attribute by name. Many common ones also mirror as properties (el.id, el.href) which can be more convenient. For custom data, use data-* attributes read via el.dataset rather than inventing attributes.

Power-ups you unlock

Quirks Mode attacks — common mistakes

Boss battleSet a data-state attribute, then read it back via dataset.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><div id="x"></div><pre id="o"></pre>
<script>const x=document.getElementById('x');x.setAttribute('data-state','active');document.getElementById('o').textContent='state='+x.dataset.state;</script></body></html>
▶ Open the interactive comic issue
‹ ClassName · ClassList · The Css HooksEvent Handlers · The Old Onclick Way ›