Menu

Working with data- attributes in JavaScript
Last Modified: May 09 2020

In the past if you wanted to store extra data in an HTML element, you would typically include it in the ID attribute and then parse it out later on in your code.

<div id='product_1'>Surface Laptop</div>
<div id='product_2'>Mouse</div>

While this works, it is prone to errors as there is no standardization in place and missing a character or using a parsing function could inevitably lead to an increase an errors.

This is where using data attributes comes into play.

The data-* attribute can be used on any element in your DOM and can be used to store any custom data that you see fit.

<div id='product_1' data-productid='1'>Surface Laptop</div>
<div id='product_2' data-productid='2'>Mouse</div>

When adding custom data attributes to your elements there are a few rules to follow:

- The data- attribute should not contain any uppercase letters
- The named portion after the data- must be at least 1 character long
- The assigned values can be any string

Accessing data- attributes in JavaScript

You can access the data attributes for each given element through the dataset property as follows:

function showData(){
	let product1 = document.getElementById('product_1');
	let id = product1.dataset.productid;
	...
}

You  can  also add data attributes to elements with the same object notation as well:

function processData(){
	let product1 = document.getElementById('product_1');
	product1.description = 'Awesome laptop';
	product2.type = 'laptop';
}

Query select custom data types

You can select elements by their custom data sets as well using the following query selector syntax:

let items = document.querySelector('[data-type="laptop"]');

The same syntax for the query selector can be used with jQuery as well.