JavaScript element.dataset Property

You are Here:

JavaScript element.dataset Property

The element.dataset property gets or sets all the custom data attributes (data-*) set on the element.

This access is available both in HTML and within the DOM.

Note: The dataset property itself can be read, but not directly written.

Get dataset

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p data-id="1245" data-user="johnsmith" data-age="35">John Smith</p> <button onclick="myFunction()">Display User Id</button> <p id="point"></p> <script> var x = document.getElementById("point"); var elem = document.getElementsByTagName("p")[0]; var txt = ""; function myFunction(){ x.innerHTML = elem.dataset.id; } </script> </body> </html>

Syntax

element.dataset

Return Values

ValueExplanation
ObjectReturns all the custom data attributes (data-*) set on the element.

Set dataset

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p data-id="1245" data-user="johnsmith" data-age="35">John Smith</p> <button onclick="myFunction()">Read All Attribute</button> <p id="point"></p> <script> var x = document.getElementById("point"); var elem = document.getElementsByTagName("p")[0]; var txt = ""; // Add John's weight; elem.dataset.weight = "50 kg"; function myFunction(){ var len = elem.attributes.length; for(var i=0; i<len; i++) txt += elem.attributes[i].name +" = "+ elem.attributes[i].value +"<br>"; x.innerHTML = txt; } </script> </body> </html>

Delete dataset

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p data-id="1245" data-user="johnsmith" data-age="35">John Smith</p> <button onclick="myFunction()">Read All Attribute</button> <p id="point"></p> <script> var x = document.getElementById("point"); var elem = document.getElementsByTagName("p")[0]; var txt = ""; // delete age delete elem.dataset.age; function myFunction(){ var len = elem.attributes.length; for(var i=0; i<len; i++) txt += elem.attributes[i].name +" = "+ elem.attributes[i].value +"<br>"; x.innerHTML = txt; } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author