How to use data attributes in JavaScript

← PrevNext →

In one of my previous blog post, I have explained about HTML data attributes and its use in Web development. Now, in this post, I'll show how to use data attributes dynamically in JavaScript. It is very simple.

image

how to use data attributes in javascript

HTML Data attributes are used to add some extra information to an element, which can later be used dynamically as and when required. These information "are kept hidden" from website visitors.

👉 You can have access to data attributes of an element by using the dataset property in JavaScript.

So, what are its practical uses or how do we use data attributes dynamically in JavaScript? I am sharing three examples here, which will give you an idea about the real benefits of using data attributes.

Let us assume, I have few <p> elements in my web page and each element has a data-attribute attached to it. I want to access the elements by its unique data attribute values.

<!DOCTYPE html>
<html>
<head>
  <style>    
    .spa::after {
      color: red;
      content: ' (sparrow)';
    }
  </style>
</head>
<body>
   <h2>List of birds.</h2>
    
   <div>
     <p class='bird' data-bird-type='dove'> Morning Dove </p>
     <p class='bird' data-bird-type='sparrow'> Abert's Tohee </p>
     <p class='bird' data-bird-type='sparrow'> Cassin's Sparrow </p>
     <p class='bird' data-bird-type='hawk'> Cooper's Hawk </p>
     <p class='bird' data-bird-type='Woodpecker'> Gila Woodpecker </p>
  </div>
  <p>
    Click the button to know which bird is of type sparrow. <br><br>
    <input type="button" id="bt" value="Click it" onclick="readAtt()" />
  </p>
</body>

<script>
  let readAtt = () => {
    let bird = document.getElementsByClassName("bird");
    
    for (i = 0; i <= bird.length - 1; i++ ) 
    {
      if (bird[i].dataset.birdType === 'sparrow') 
      {
        bird[i].classList.add('spa');    // add a new class or another class to the element.
      }
    }
  }
</script>
</html>
Try it

In the above script, I am using the dataset property to access data attribute associated with the <p> elements. The "dataset" returns a DOMStringMap object that contains data attributes of an element. The dataset output in the console window will look like this. See the image.

DOMStringMap object in JavaScript

Using each elements data attribute, the script will check for a specific bird type and take action accordingly.

In-addition, you can use the getAttribute() method to access a data attribute.

if (bird[i].getAttribute('data-bird-type') === 'sparrow') 
{
    bird[i].classList.add('spa');    // add a new class or another class to the element.
}

Similarly, you can access mulitple data attributes of elements in JavaScript. For example,

<body>
   <h2>List of birds</h2>
    
  <div>
    <p class='bird' data-bird-type='dove' data-scientific-name='Zenaida Macroura'> Morning Dove </p>
    <p class='bird' data-bird-type='sparrow' data-scientific-name='Melozone Aberti'> Abert's Tohee </p>
    <p class='bird' data-bird-type='sparrow' data-scientific-name='Peucaea Cassinii'> Cassin's Sparrow </p>
    <p class='bird' data-bird-type='hawk' data-scientific-name='Accipiter Cooperii'> Cooper's Hawk </p>
    <p class='bird' data-bird-type='Woodpecker' data-scientific-name='Melanerpes Uropygialis'> Gila Woodpecker </p>
  </div>
  
  <p>
    Click the button to <b>learn</b> more about each bird using its data attributes<br><br>
    <input type="button" id="bt" value="Click it" onclick="readAtt()" />
  </p>

  <p id='info'> </p>
</body>

<script>
  let readAtt = () => {
    let bird = document.getElementsByClassName("bird");
    document.getElementById('info').innerHTML = ""
    
    for (i = 0; i <= bird.length - 1; i++ ) {
      let brdType = bird[i].dataset.birdType;
      let brdSciName = bird[i].dataset.scientificName;
      
      document.getElementById('info').innerHTML += 'Bird -' + bird[i].innerHTML + '(<b>Type</b>: ' + brdType + ', ' + 
        '<b>Scientific Name</b>: ' + brdSciName + ') <br />';
    }
  }
</script>
Try it

Now, let's take this to the next label and make it more dynamic and useful. In my next example, I'll use data attributes of each element to extract more information from a remote JSON file.

To extract data from a JSON file, I am using async and await.

<!DOCTYPE html>
<html>
<body>
  <h2>List of birds.</h2>
  <p>
    Click a bird name to see more birds in its category.
  </p>

  <div>
    <p class='bird' data-bird-type='Dove'> Morning Dove </p>
    <p class='bird' data-bird-type='Sparrow'> Abert's Tohee </p>
    <p class='bird' data-bird-type='Hawk'> Snail Kite </p>
    <p class='bird' data-bird-type='Woodpecker'> Gila Woodpecker </p>
  </div>

  <p id='t1'> </p>
</body>
<script>
  window.addEventListener('click', function (e) {
    if (e.target.className === 'bird') {
      get_details(e.target.dataset.birdType);
    }
  });

  // Based on data attribute values, get more data from a JSON file.
  let get_details = async(brdType) => {
    let url = "../../library/birds.json"
    let response = await fetch (url);
    const arr = await response.json();

    document.getElementById('t1').innerHTML = '<b>More ' + brdType + '</b><br><br>';
    
    for (let i = 0; i < arr.length - 1; i++) {
      if(arr[i].Type === brdType) {
        document.getElementById('t1').innerHTML += arr[i].Name + '<br>';
      }
    }
  }
</script>
</html>
Try it

Happy coding. 🙂

← PreviousNext →