Hello, my name is: Amy

What are data- attributes good for?

To start, let it be known that I have never really fought the good fight in a world without data- attributes. I've always worked with them right by my side. I don't have a full appreciation for the creativity and madness involved in previously pass all this data around.

So, real quick, an attribute is anything in html that can modify, or provide more information for, an element. So, href, alt, class, id, etc are all attributes. data-* is also an attribute, but the cool thing is that you aren't boxed in by what is already available, and where the * is you can add (kindof) whatever you might want.

Before data-, people would just add their own attributes, which is not-so-standard. Data attributes provided a standardized way to extend the information that can be associated with a particular element.

They are written like:

<p data-category="fancy" data-is-cool="true">Fancy words</p>

data- in the wild

To get right into it, I recently built a single web page that contained a quiz. I needed to know which result was chosen so some different styles/scripts could run. Instead of just adding a 'result-XXX' class to the quiz container, I opted to add the result name as a data- attribute.

It seemed a little cleaner to me, and this way I could target the quiz with result-specific css AND run scripts that needed the result name (without having to parse the classList each time to see which result was given.

Starting out, there is nothing populated in the data-result attribute on the <section> element. Here's kind of how that looked:

<section id="quiz" data-result="">
  <div class="questions"></div>
  <div class="results"></div>

Using data- with JavaScript

All these data- properties are stored in an object, that is accessible through accessing the dataset of the element. When a result was displayed, I added the result ID to the data-result attribute like so:

var quiz = document.getElementById('quiz');
quiz.dataset.result = 'resultA';

//for a two-word attribute:
quiz.dataset.twoWords = 'yes';

When the user decided to re-take the quiz, I didn't need to remove the previous result, I just replaced the value of data-result:

quiz.dataset.result = 'resultB';

Because data-result is still an attribute, I could have also used quiz.setAttribute('data-result', 'resultB');

Using data- with css

I also needed to do some styles that were reliant on the result. You can target specific data- attributes like:

.quiz[data-result="resultB"] {
  background-color: deeppink;

Don't go crazy

Be careful when using these that you don't forget to first rely on the semantic nature of HTML, and then extend as necessary with data- attributes. So, if you find yourself doing something that feels icky, probably don't do that.

If you feel like playing around with this yourself, here's the code from this quiz example:

See the Pen data-attributes by Amy Etheredge (@theaemarie) on CodePen.