Did you ever use some weird class like
HTML5 Spec, we can use something better for this, and it's called Data Attributes!
Let's dive into using Data Attributes together.
HTML Markup permalink
<div id="demo" data-user="fuu" data-custom-emoji="🔥"></div>
Very simple, for each element we want to add, we can use
data- with a name, note we use multiple dashes for spaces.
HTML5 brings us the wonderful Dataset API, much like the
classList, as we explored before. But it's not quite as impressive.
We can only get and set data.
Getting a Data Attribute permalink
To get a data attribute we can use the following code:
var element = document.getElementById('demo');
Pretty cool right!
Note that we have to use
camelCase to retrieve the data, while we inputted as
dash-style. This is the rule, and we have to obey to it.
Setting Data Attributes permalink
To set, we use the same Dataset API
element.dataset.customEmoji = '⚡️';
element.dataset.bar = 'Fuu?';
As you can see, we can easily overwrite data attributes, or even add new ones!
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 to
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!
See the following Codepen for all these examples:
Browser support permalink
Really good browser support for Dataset, so why not use it!