The HTMLElement.dataset property in vanilla JavaScript
A few weeks ago, I wrote about what you can do with data attributes in JavaScript.
The focus was on different strategies for using data attributes, rather than how to get and set them, but I had a lot of folks write to me asking why I didn’t talk about the HTMLElement.dataset
property.
So, let’s talk about that today!
What the HTMLElement.dataset
property does
The HTMLElement.dataset
property provides a quick-and-easy way to get and set data attributes on elements.
The dataset
property returns a DOMStringMap
of key/value pairs. Each key is the data attribute name without the leading data-
, and the value is the value of the attribute.
For example, imagine you have an element like this…
<button data-sandwich="tuna" data-topping="tomato" data-snack="cookies">Place Order</button>
You can get all of the data attributes on that element in one go using the dataset
property, like this…
let btn = document.querySelector('button');
// returns {sandwich: tuna, topping: tomato, snack: cookies}
let atts = btn.dataset;
You can also get individual data attributes using dot notation on the dataset
property, like this…
let sandwich = btn.dataset.sandwich;
And you can pair it with object destructuring to set variables…
let {topping, snack} = btn.dataset;
You can also set individual data attributes using dot notation.
btn.dataset.side = 'chips';
Why I don’t usually write about this
I tend to use the Element.*Attribute()
methods (get
, set
, etc.) a lot more than dataset
, for a few reasons…
- Muscle memory. I’ve been using them longer, so they fly off my fingers faster and easier.
- The
HTMLElement.dataset
property only works with data attributes, whereasgetAttribute()
and so on work with any attribute. This reinforces point one about muscle memory. - Cognitive overhead. Because the
dataset
property drops the leadingdata-
(which I know is a feature), it introduces more cognitive load on my ADHD brain. As a result, I’m more prone to typing properties wrong when using it.
This is 100% a personal preference thing, though. If you like the dataset
property, definitely use it!