Set & Get Data Attributes In Javascript (Simple Examples)

Welcome to a quick tutorial on how to set and get data attributes in Javascript. Want to insert your own custom property or data into HTML elements?

  • To set data attributes in HTML, we define data-KEY="VALUE" in the start tag. For example, <div data-color="red">
  • We can set data attributes in Javascript using the dataset property. For example, document.getElementById("ID").dataset.color = "red";
  • Lastly, access the data attributes in Javascript using the same dataset property. For example, var color = document.getElementById("ID").dataset.color;

That covers the basics, but read on for more examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TLDR – QUICK SLIDES

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

GET & SET DATA ATTRIBUTES

All right, let us now get into the examples of how to work with the data attributes in Javascript.

 

1) SET DATA ATTRIBUTE

1-set.html
<!-- (A) SET DATA ATTRIBUTE IN HTML START TAG -->
<div id="demoA" data-color="red">
  This element has custom data attributes.
</div>
 
<!-- (B) SET DATA ATTRIBUTE IN JAVASCRIPT -->
<script>
document.getElementById("demoA").dataset.priority = "high";
// <div id="demoA" data-color="red" data-priority="high">
</script>

As in the introduction above, there are 2 ways to set HTML data attributes:

  1. Directly in the HTML start tag itself data-KEY="VALUE".
  2. Using Javascript ELEMENT.dataset.KEY = "VALUE".

Yes, we can have multiple data attributes attached to a single element.

 

2) GET DATA ATTRIBUTE

2-get.html
<!-- (A) ELEMENT WITH DATA ATTRIBUTES -->
<div id="demoB" data-color="red" data-priority="high">
  This element has custom data attributes.
</div>
 
<!-- (B) GET DATA ATTRIBUTE IN JAVASCRIPT -->
<script>
var el = document.getElementById("demoB");
console.log(el.dataset.color); // red
console.log(el.dataset.priority); // high
</script>

This one is as straightforward as can be. We can also retrieve the data using the same ELEMENT.dataset.KEY.

 

 

3) SET ARRAYS INTO DATA ATTRIBUTE

3-array.html
<!-- (A) DUMMY ELEMENT -->
<div id="demoC">Dummy</div>
 
<!-- (B) JAVASCRIPT -->
<script>
// (B1) GET HTML ELEMENT
var el = document.getElementById("demoC");

// (B2) SET ARRAY TO DATA ATTRIBUTE
// dataset can only be string - json.stringify() to turn array to string
el.dataset.array = JSON.stringify(["Red", "Green", "Blue"]);
 
// (B3) GET ARRAY BACK FROM STRING
// use json.parse() to turn encoded string back to array
console.log(JSON.parse(el.dataset.array));
</script>

A quick note, HTML data attributes must be a string and will not accept arrays/objects.

  • To set an array into the data attribute, we use JSON.stringify() to encode the array into a string first.
  • To retrieve the data, we use JSON.parse() to turn the string back into an array.

 

4) STORE HTML SNIPPETS IN DATA ATTRIBUTE

4-html.html
<!-- (A) DUMMY ELEMENTS -->
<div id="demoD" data-snippet="<strong>Foo</strong>">Demo D</div>
<div id="demoE">Demo E</div>

<!-- (B) JAVASCRIPT -->
<script>
// (B1) GET HTML SNIPPET
var snippet = document.getElementById("demoD").dataset.snippet;
 
// (B2) SET HTML SNIPPET
document.getElementById("demoE").innerHTML = snippet;
</script>

Yes, we can set an HTML snippet into data attributes… But the question is, why? If you want to use it as an HTML template, <template> is better for performance and it makes more sense.

 

 

5) SET CSS STYLE BASED ON DATA ATTRIBUTE

5-style.html
<!-- (A) CSS STYLES -->
<style>
div[data-color="red"] { background: red; }
div[data-color="green"] { background: green; }
div[data-color="blue"] { background: blue; }
</style>

<!-- (B) DUMMY ELEMENT -->
<div id="demoF">Dummy</div>
 
<!-- (C) JAVASCRIPT SET COLOR -->
<script>
function setColor (col) {
  document.getElementById("demoF").dataset.color = col;
}
</script>
<input type="button" value="Red" onclick="setColor('red')"/>
<input type="button" value="Green" onclick="setColor('green')"/>
<input type="button" value="Blue" onclick="setColor('blue')"/>

This final example is an extra bit to demonstrate how CSS can also be used to target different data attributes – Kind of useful, but I personally still prefer to stick with CSS classes and variables.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECK

Data attributes are well supported in almost every browser.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Set & Get HTML Data Attribute (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.