JavaScript Interview Question #58
How do getAttribute(), setAttribute(), and dataset work?
DOM, Events & Event Loop Fundamentals Mid-Level Intermediate
Quick Interview Answer
getAttribute reads an attribute's string value, while setAttribute creates or updates an attribute. For custom data-* attributes, dataset provides a convenient object-style interface.
Detailed Explanation
getAttribute reads an attribute's string value, while setAttribute creates or updates an attribute. For custom data-* attributes, dataset provides a convenient object-style interface.
A data-user-id attribute is exposed as element.dataset.userId. Data attribute values are strings, so convert them when numeric or Boolean semantics are required.
Code Example
const button = document.querySelector("#editButton");
button.setAttribute("aria-label", "Edit user");
const label = button.getAttribute("aria-label");
button.dataset.userId = "42";
const userId = Number(button.dataset.userId);