Did you ever use some weird class like
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
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
var element = document.getElementById('demo');
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?';
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
As you can see, this method needs the
Using Data Attributes in CSS permalink
Another strong value for data attributes is that they can be accessed in CSS!
Look at this example:
Wow, what can these bad boy data attributes not do right!
Browser support permalink
Really good browser support for dataset, so why not use it!