JavaScipt - Using data attributes of an element to get data from JSON file

← PrevNext →

In this article I am sharing an example showing how to get data attributes of an element using JavaSript and using the data to extract related information from a remote JSON file.

I have previoulsy explained in detail on how to use data attributes in JavaScript.

👉 What is data attribute in HTML? Learn more about data attributes and its practicle usages.

Data attributes of an element can be accessed using the dataset property. I am using the "dataset" property in the below example.

<body>
  <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>  <!--show the extracted data here-->
</body>
<script>
  window.addEventListener('click', function (e) {
    if (e.target.className === 'bird') {
      get_details(e.target.dataset.birdType);
    }
  });

  // Using 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>
Try it

In the markup section, I have few <p> elements each having a data attribute named data-bird-type. Each attribute has distinct value. Its a type of bird.

I have a JSON file on a remote server. So, when a user clicks on a particular type of bird, it should fetch related data from the JSON file and show it.

In the script section, the first thing you will notice is that I have an event listener to capture click events. It will get the bird type (from the data attributes that I have defined in each elemnet) and call a function to fetch related data from a remote JSON file.

See how I am using the "dataset" property.

get_details(e.target.dataset.birdType);

I am using async and await methods to read and extract data from a remove file.

In-addition, I am using getElementById() method to get the id of the element that will show the extraced data.

Happy coding. 🙂

← PreviousNext →