Set & Get HTML Data Attributes In Javascript – Simple Examples

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

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

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes HTML Data Useful Bits & Links
The End

 

DOWNLOAD & NOTES

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

 

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.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

HTML DATA ATTRIBUTES

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

 

1) SET HTML DATA ATTRIBUTES

1-set.html
<!-- (A) DIRECTLY DEFINE DATA ATTRIBUTE IN OPEN TAG -->
<div id="demoA" data-color="red">
  This element has custom data attributes.
</div>
 
<!-- (B) WE CAN ALSO ASSIGN IN JAVASCRIPT -->
<script>
// <div id="demoA" data-color="red" data-priority="high">
document.getElementById('demoA').dataset.priority = "high";
</script>

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

  1. Directly in the opening HTML tag itself data-KEY="VALUE".
  2. Or using Javascript ELEMENT.dataset.KEY = "VALUE".

Yes, just in case you have not noticed, we can have multiple data attributes attached to a single element.

 

2) GET HTML DATA ATTRIBUTE IN JAVASCRIPT

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');
var color = el.dataset.color;
var priority = el.dataset.priority;
console.log(color);
console.log(priority);
</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) SET ARRAY TO DATA ATTRIBUTE
function set () {
  var arr = ["Red", "Green", "Blue"];
  // DATASET CAN ONLY BE A STRING
  // WE USE JSON.STRINGIFY() TO ENCODE ARRAY TO STRING
  arr = JSON.stringify(arr);
  console.log(arr);
  document.getElementById('demoC').dataset.arr = arr;
}

// (B2) GET ARRAY BACK FROM STRING
function get () {
  var arr = document.getElementById('demoC').dataset.arr;
  // JSON PARSE TO TURN ENCODED STRING BACK TO ARRAY
  arr = JSON.parse(arr);
  console.log(arr);
}
</script>
<input type="button" value="Set Array" onclick="set()"/>
<input type="button" value="Get Array" onclick="get()"/>

No, the HTML data attribute must be a string and will not accept arrays/objects.

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

 

4) STORING HTML SNIPPETS

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

<!-- (B) JAVASCRIPT -->
<script>
function getHTML () {
  // (B1) GET HTML SNIPPET
  var snippet = document.getElementById('demoD').dataset.snippet;
 
  // (B2) SET HTML SNIPPET
  document.getElementById('demoE').innerHTML = snippet;
}
</script>
<input type="button" value="HTML Snippet" onclick="getHTML()"/>

Yes, we can set an HTML snippet into data attributes… But the question is, why? Does it make any sense?

 

 

5) STYLE BASED ON DATASET

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 setCol (col) {
  document.getElementById('demoF').dataset.color = col;
}
</script>
<input type="button" value="Red" onclick="setCol('red')"/>
<input type="button" value="Green" onclick="setCol('green')"/>
<input type="button" value="Blue" onclick="setCol('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.

 

 

USEFUL 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.

 

INFOGRAPHIC CHEAT SHEET

Set & Get HTML Data Attribute (click to enlarge)

 

LINKS & REFERENCES

 

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. Required fields are marked *