How To Use Data Attributes In JavaScript, CSS + HTML

The smart way to store additional information on the DOM

Alexandra Ortiz
Dec 22, 2020 · 5 min read
Image for post
Image for post
Photo by Franki Chamaki via Upsplash

This article is a short and quick guide to using data attributes in JavaScript— something I wish I knew more about when I was beginning my own JavaScript journey.

Data attributes are actually HTML attributes that allow you to create and assign bespoke data points to HTML elements. They are accessible via HMTL, CSS, and JavaScript, making them a powerful choice for storing bits of information that maybe aren’t so appropriate for class lists or ids. After all, we should aim to keep class and id attributes reserved for styling purposes, otherwise, things can get very messy and confusing quickly.

Identifying data attributes in HTML is pretty easy, just look for anything in the HTML element tags that has data-something. The something, in this case, can be anything you want under the sun although it is best practice to name it expressively so that you, and other programmers using your code, can easily tell what type of information is being stored in that data attribute. To create a data attribute in HTML, simply start the property with data- and pick a name that makes sense for you. You will want to use the assignment operator, = , to set the data attribute value to a string. If your data attribute requires two or more words, just add a dash between each word. For example, If I wanted to create a data attribute called “trainer id”, I would write it as data-trainer-id in the desired HTML element.

In the code below, we can see this very example hardcoded into the HTML. I decided to add data attributes to the different lis in my unordered list so I could associate the trainer id of each pokemon. By doing this, I can easily retrieve information on what pokemon belongs to what trainer, and quickly apply JavaScript or CSS changes as needed.

Image for post
Image for post
Screenshot of Chrome devTools showing the data attributes associated with each li element

The data attribute will not appear in your browser so there is no need to worry if our users will see it.

While you can hardcode your data attributes in HTML, it is best practice to create them in JavaScript so that the values remain dynamic. Below is a screenshot of a data attribute being created as part of a button element.

Image for post
Image for post

A quick breakdown of what is happening in the code above for more context:

  • The function renderPokemon() is taking in a data parameter, which is an array of objects in this case.
  • The function is then applying the .forEach() method to iterate over each object in the data array.
  • In each iteration, we are creating an li element and populating it with the element’s nickname and species attributes, as well as creating a button that has a data attribute pointing to that element’s id. In this case, the data attribute is called data-pokemon-id.

**Phew*** ok, back to data attributes…

In this scenario, we are still hardcoding the HTML code for the data attribute but applying the value of that attribute dynamically. Doing this in our JavaScript file allows us more control, versatility, and usability over the data attributes. BUUUUT, we can do this better…

We can actually use dot notation in JavaScript to create and assign data attributes, all it takes is a slight change in syntax. When using JavaScript, we now work with dataset instead of data- and we switch to camel case, thisIsCamelCase, when creating a data attribute with more than one word.

Image for post
Image for post

In the code above, we kept it simple and assigned the trainerDiv element a data attribute of id. This is done by using dot notation, .dataset, followed by the desired name for the attribute. If we wanted to use dot notation to create or assign a data attribute with more than one word, say “trainer id”, then it would look like this: trainerDiv.dataset.trainerId. The result in HTML would look exactly like our first example where we hard coded the data attribute into the element tag.

Image for post
Image for post
Screenshot shows the creation of a new element, newLi, and a new data attribute called “trainer id”

Once my newLi is added to the DOM, I can search for that node using traditional DOM traversal techniques, such as .querySelector()

Image for post
Image for post
Used .querySElector to find the data attribute we just set.

Or, if we have the element already in hand, we can check it’s data attributes by using dot notation again!

Image for post
Image for post
The console returns the DOMStringMap object where data attributes are stored in JavaScript.

Don’t worry about DOMStringMap in the screenshot above, that is just the interface that is used for the HTML.dataset attribute (aka, we get .dataset from the DOMStringMap).

Finally, since data attributes are just plain HTML properties, we can use these data attributes in CSS too. For example, we could target the li elements that have data-trainer-id = "8" and data-trainer-id = "12" to apply style changes depending on the trainer's id.

Image for post
Image for post
CSS targeting data attributes of specific values for style changes.

TLDR; data attributes are a great way to store additional data that does not fit/should not be in either id or class attribute of an HTML element. Data attributes can be created and assigned in HTML or JavaScript using the following syntax:

  • HTML: data-some-name = "value" (use dashes)
  • JavaScript: element.dataset.someName = "value" (use .dataset and camelCase)

Data attributes can be accessed via dot notation or using DOM traversal techniques such as .querySelector():

  • element.dataset
  • element.querySelector('[data-some-name = "value"]') with value being the actual value you are looking for (e.g., 9, “fluffy”, etc.)

Data attributes can be used by CSS to apply style changes as well.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store