freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #7 of 21

attributes · getAttribute · setAttribute · dataset

NodetteVSThe Event Bubbler
Nodette saysRead/write attributes with getAttribute/setAttribute, and custom data via dataset.

getAttribute/setAttribute/removeAttribute handle any HTML attribute. Many map to DOM properties too (el.id, el.href). Custom data-* attributes read off el.dataset in camelCase (data-user-id → dataset.userId) — the clean way to stash app data on elements.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleSet a data-state attribute and 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.dataset.userId='42';
document.getElementById('o').textContent='data-user-id = '+x.dataset.userId;</script></body></html>
▶ Open the interactive comic issue
‹ Removing Elements · Remove · RemoveChildClasses · ClassList · Add · Remove · Toggle ›