Get A Data Attribute From The Event Object In JavaScript

In this article, we will cover how to get a data attribute from the event object in JavaScript. To achieve this, we need to use the `target.dataset` property to access data attributes from the `event` object. The `dataset` property returns a `Map` of strings.

For this tutorial, we can use some HTML code, to create an element and assign a data attribute to it, but we are going to do this using JavaScript. First, let’s create our HTML element which will be a `<div>` container and assign it a data attribute.

Get A Data Attribute From The Event Object In JavaScript

This is our HTML layout which contains our main container which is a `<div>` element with `id=’app’` –

<!DOCTYPE html>

<html>

<head>

  <title>Parcel Sandbox</title>

  <metacharset="UTF-8"/>

</head>

<body>

  <div id="app"></div>

  <script src="src/index.js">

  </script>

</body>

</html>

Now, we need to create a new `<div>` element and append it inside the main `<div>` container. We will use `createElement()` method to create our new element and `appendChild()` method to append it to our main container.

const container = document.querySelector("#app");

const element = document.createElement("div");

container.appendChild(element);

We will add some text to our element so that we can see it on screen.

element.innerHTML = "Data attributes Tutorial";

Then, we need to assign data attributes to our `element`. We will use the `dataset` property and define the data attribute we would like to add to the element. We will assign two data attributes to our element – `test` and `anotherTest`.

element.dataset.test = "test data";

element.dataset.anotherTest = "another data";

Next, we need to attach an `eventListener` to our element. For our case, we will listen for `click` events so that we can access the `event` object and get the data attributes attached to the element –

element.addEventListener('click', (event) => {

  console.log(event.target.dataset)

})

Now, if we clicked on the element we created which contains “Data attributes tutorial” text, we should get an object that contains the data attributes we attached to the element.

We can also get specific data attributes using the `getAttribute()` method –

element.addEventListener("click", (event) => {

  console.log(event.target.getAttribute("data-test"));

});

Note that we have to prefix our attributes with “data-“

Leave a Reply