Skip to main content

How to Get Data Attributes from an Event Object in JavaScript

Custom data-* attributes in HTML are a powerful way to store extra information on an element without cluttering up classes or IDs. When a user interacts with these elements, you often need to access this data from the JavaScript event object to determine what action to take.

This guide will teach you the two primary methods for retrieving data-* attributes from an event target. You will learn the modern, recommended approach using the dataset property, as well as the more general-purpose getAttribute() method. Understanding both will allow you to handle any event-driven interaction with custom data cleanly and efficiently.

What are data-* Attributes?

data-* attributes are a standard way to embed custom, private data on an HTML element. The syntax is simple: any attribute that starts with data- is a valid data attribute.

<button id="user-btn" data-user-id="12345" data-action="delete-user">
Delete User
</button>

In this example, we've stored a user-id and an action directly on the button. Our goal is to retrieve these values when the button is clicked.

##Method 1 (Recommended): Using event.target.dataset

The dataset property on an HTML element is the modern and most convenient way to access all data-* attributes. It returns a DOMStringMap object containing all the element's data attributes.

The logic JavaScript automatically converts the data-* attribute names from "kebab-case" to "camelCase" for you to use as keys on the dataset object.

  • data-user-id becomes dataset.userId
  • data-action becomes dataset.action

The solution:

const btn = document.getElementById('user-btn');

btn.addEventListener('click', (event) => {
// event.target is the button element that was clicked
const userData = event.target.dataset;

// The dataset property is a DOMStringMap object
console.log(userData); // Output: { userId: "12345", action: "delete-user" }

// Access specific properties using camelCase
const userId = userData.userId;
const action = userData.action;

console.log(`User ID: ${userId}`); // Output: User ID: 12345
console.log(`Action: ${action}`); // Output: Action: delete-user
});

Method 2: Using event.target.getAttribute()

The getAttribute() method is a more general-purpose way to read any attribute from an HTML element, including data-* attributes.

The logic:

  • When using getAttribute(), you must provide the full and exact name of the attribute you want to read.

The solution:

const btn = document.getElementById('user-btn');

btn.addEventListener('click', (event) => {
// event.target is the button element

// You must use the full attribute name
const userId = event.target.getAttribute('data-user-id');
const action = event.target.getAttribute('data-action');

console.log(`User ID: ${userId}`); // Output: User ID: 12345
console.log(`Action: ${action}`); // Output: Action: delete-user
});
note

If the attribute does not exist on the element, getAttribute() will return null.

Key Differences: dataset vs. getAttribute()

While both methods work, dataset is purpose-built for this task and is generally preferred.

Featureevent.target.datasetevent.target.getAttribute()
SpecificityWorks only for data-* attributes.Works for any HTML attribute (id, class, href, etc.).
NamingAutomatically converts names to camelCase (e.g., dataset.userId).Requires the full, original attribute name (e.g., 'data-user-id').
Return TypeReturns a DOMStringMap object with all data-* attributes.Returns a string value for a single attribute, or null if not found.
note

Rule of Thumb: Use dataset when you are working with data-* attributes. Use getAttribute() when you need to read other standard HTML attributes like href or aria-label.

Practical Example: A Dynamic Button Handler

This example uses event delegation to handle clicks on multiple buttons. The dataset property allows a single event listener to determine what action to perform for each button.

The HTML:

<div id="user-list">
<button class="user-action" data-user-id="101" data-action="edit">Edit User 101</button>
<button class="user-action" data-user-id="102" data-action="delete">Delete User 102</button>
<button class="user-action" data-user-id="103" data-action="view">View User 103</button>
</div>

The JavaScript:

const userList = document.getElementById('user-list');

userList.addEventListener('click', (event) => {
// Only act if a button was clicked
if (event.target.tagName === 'BUTTON') {
const userId = event.target.dataset.userId;
const action = event.target.dataset.action;

if (action === 'edit') {
console.log(`Redirecting to edit page for user ${userId}...`);
} else if (action === 'delete') {
console.log(`Opening delete confirmation for user ${userId}...`);
} else {
console.log(`Showing details for user ${userId}...`);
}
}
});

Conclusion

Accessing data-* attributes from an event object is a fundamental technique for creating interactive and dynamic web pages.

  • The event.target.dataset property is the modern and recommended method. It is specifically designed for data-* attributes and is convenient to use due to its automatic camelCase conversion.
  • The event.target.getAttribute() method is a more general-purpose tool that also works but requires the full attribute name.

By using dataset, you can write cleaner, more readable, and more efficient event-handling logic.