Image for post

HTML5 gave us the ability to add arbitrary pieces of information called data attributes to an element to use behind the scenes for any purpose you wish, and here I will demonstrate how to use them in JavaScript.

I put data attributes to good use in my Interactive Periodic Table. There is plenty of information around on the topic but often with simplistic or contrived examples so here I will present a real-world usage with a simplified version of the Periodic Table.

You can add a custom data attribute to an element by hard-coding it into the HTML, prefixing the name with data-, for example:

<div id=”div1" data-manufacturer=”nikon” data-model=”d6">Nikon D6</div>

In JavaScript you can access an element’s data attributes for reading and writing using its dataset property which is of DOMStringMap type and is basically a collection of key/value pairs. The keys are the names used for the attributes but without the data- prefix, so for the above example we would use manufacturer and model, as shown below.

const element = document.getElementById(“div1”);

console.log(element.dataset.manufacturer); // nikon
console.log(element.dataset.model); // d6
element.dataset.manufacturer = “canon”;
element.dataset.model = “EOS 90D”;

It is also easy to find elements with certain data attribute values using querySelector, for example:

const element = document.querySelector(“[data-manufacturer=’nikon’][data-model=’d6']”);

#coding #web-development #programming #javascript #webdev #html5

Using HTML5 Data Attributes with JavaScript
1.55 GEEK