Get and Set Data Attributes with JavaScript
permalinkDid you ever use some weird class like class="user-fuu"
for JavaScript
to then pick up this class?
Since the HTML5
specification, we can use something better for this, and it's called data attributes!
Let's dive into data attributes and get an HTML element with them.
HTML Markup permalink
<div id="demo" data-user="fuu" data-custom-emoji="π₯"></div>
This is a very simple example. For each element we want to add, we can use a data attribute data-
with a name. Note we use multiple dashes instead of spaces.
Vanilla JS get element with the dataset API permalink
So HTML5
brings us the wonderful Dataset API, much like the classList
, as we explored before. But it's not quite as impressive.
We can use it to get and set data attributes.
Getting a Data Attribute permalink
To get the value from a data attribute in JavaScript we can use the following code:
const element = document.getElementById('demo');
console.log(element.dataset.user);
console.log(element.dataset.customEmoji);
// fuu
// π₯
Pretty cool right!
Note that, to get the data from the attribute we have to use camelCase
writing in our code for the attributes with multiple dashes. That's the rule.
Setting Data Attributes permalink
To set the value of data attribute, we use the same dataset API again:
element.dataset.customEmoji = 'β‘οΈ';
element.dataset.bar = 'Fuu?';
console.log(element.dataset.customEmoji);
console.log(element.dataset.bar);
// β‘οΈ
// Fuu?
As you can see, we can easily overwrite data attributes and even add new values!
Magic powers and trust me, you will use this quite often.
Alternative method setAttribute and getAttribute permalink
An alternative is using setAttribute
and getAttribute
methods in JavaScript.
element.setAttribute('data-custom-emoji', 'π€');
console.log(element.getAttribute('data-custom-emoji'));
// π€
As you can see, this method needs the dash-style
again.
Using Data Attributes in CSS permalink
Another strong value for data attributes is that they can be accessed in CSS!
Look at this example:
[data-user] {
width: 50px;
height: 50px;
background: teal;
border-radius: 50%;
}
Wow, what can these bad boy data attributes not do right!
See the JavaScript code examples in this Codepen permalink
See the Pen Vanilla JS Data Attributes set and get by Chris Bongers (@rebelchris) on CodePen.
Browser support permalink
Really good browser support for dataset, so why not use it!
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter