dataset property

Get custom data values defined using the "data-" prefix on an element with the dataset property.

This property is read-only.

IE11

 

Syntax

JavaScript
data = object.dataset

 

Property values

Type: DOMStringMap

A DOMStringMap of data attribute values for an element.

Remarks

Custom data attributes can be assigned to elements using a data- prefix followed by the name, such as data-contoso-numbers="" . To create a custom data attribute on a div element, do this: <div data-contoso-numbers="Some data here"></div>

The dataset names are read only, but you can change the value they represent. To get or set the value of any given data attribute, you use the following syntax:


   // to get
   var myData = element.dataset.contosoNumbers;
   // to set
   element.dataset.contosoNumbers = "something new";

If the name of the custom data attribute is hyphenated, it is converted to camel case. In this case, to access the data-contoso-numbers attribute, you'd use element.dataset.contosoNumbers. The data- prefix is dropped.

Examples

This example uses dataset to track values on a div representing a spaceship in a space game. The example defines several custom data attributes. When you click the Fire button, the shields value on the "ship" are reduced by 25. When the shields value hits zero, the ship turns red and the fire button is disabled.


<!DOCTYPE html>
<html>
<head>
    <title>Dataset test</title>
  <style>
    div {
      display:block;
      border: solid 2px green;
      width:200px;
      height:200px; 
      text-align:center;    
    }
    button {
      position:absolute;
      top:250px;
    }

  </style>
</head>
<body>
  <!-- This div element contains four custom data attributes -->
  <div id="spacegame" 
    data-shipid="Infinity" 
    data-weapons="magnetic accelerator cannons"  
    data-shieldvalue="100"
    data-registry="INF 101">
    UNSC Infinity</div>      
  <button id="shootNow" onclick="Shoot();"> Fire </button>   
  <script>
      //  get the div element
      var myDiv = document.getElementById('spacegame');
      
      // function to subtract the shield value
      function Shoot() {
        var shieldsRemaining = parseInt(myDiv.dataset.shieldValue); 
        shieldsRemaining =- 25;  // subtract 25%
        // if shields are below 25%, ship is destroyed
        if (temp < 25){
          myDiv.textContent = "The " + myDiv.dataset.shipId + " is now destroyed"; // signal ship is gone
          myDiv.style.backgroundColor = "red"; // change color of block
          document.getElementById("shootNow").disabled = true; // don't allow any more input
        } else {
          myDiv.dataset.shieldValue = temp.toString();
        }         
      }      
      </script>
</body>
</html>

See also

HTMLElement

 

 

Show:
© 2014 Microsoft