Lesson learned — dataset keys are camel-cased
This quick post tells the story of how I learned that dataset keys are camel-cased. Unfortunately, it is a little rant about implementations that want to provide convenience by extending the standard but make things more confusing.
Baseline: Dataset is widely available
- Google Chrome
7 2010.10.19
- Microsoft Edge
12 2015.07.29
- Firefox
6 2011.08.16
- Safari
5.1 2011.07.20
Accessing data-* attributes via dataset
HTML data-* attributes allow us to store arbitrary info on element declaration. It is also easy to retrieve these data via JavaScript dataset attribute. The dataset attribute is an object that contains all data-* values. According to the element.dataset specifications, all keys of this object are camel-cased.
<div id="coolDiv" data-value="🥑" data-cool-value="🍆"></div>
console.log(coolDiv.dataset.value)
// 🥑
console.log(coolDiv.dataset.coolValue)
// 🍆
Safari wants to make it easier, but…
I don’t work with datasets often, so while implementing some changes on the NN1 Dev Club, I forgot about the camel case conversion rule and referenced all the values via original dash-separated names.
console.log(coolDiv.dataset['value'])
// 🥑
console.log(coolDiv.dataset['cool-value']) // 👈 don't do that
// 🍆
This style works just fine in Safari, which is my default browser. I implemented a feature, tested it, submitted a change and called it a day. Leave your suggestions for E2E tests for another day, please 😜
Unfortunately, this implementation is incorrect and does not follow the specification. It could be logical and even more intuitive, but it is against the spec and caused more confusion than anything else. Lesson learned — dataset keys are camel case 👍