HTML & CSS · Junior · Question 7 of 75
How do you read the value of the data-user-id="42" attribute in JavaScript?
- 1
element.dataUserId - 2
element.data.userId - ✓Correct answer:
element.dataset.userId
Explanation
All data-* attributes are available through element.dataset, with kebab-case names converted to camelCase: data-user-id → dataset.userId. The value is always a string. You can also use getAttribute('data-user-id'). In CSS they are accessed via the [data-user-id] selector and the attr() function.