Access data attributes in HTML element

Data set attributes

You can work with these data-* attributes in the DOM via the dataset property. The dataset property returns an array of values, indexed by the custom part of the name.

Example


<!DOCTYPE HTML> 
<html> 
    <body> 
        <p id="textblock" 
           class="Survey numbers" 
           data-Survey="apple" 
           data-sentiment="like"> 
            This is a test.<!--from  ww  w.ja v  a  2  s  .  c o m-->
        </p> 
        <script> 
            
            var elem = document.getElementById("textblock"); 
            for (var attr in elem.dataset) { 
                document.writeln(attr); 
            } 
            document.writeln("Value of data-Survey attr: " + 
                         elem.dataset["Survey"]); 
        </script> 
    </body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window