Last updated: Mar 4, 2024
Reading timeยท2 min
Use the target.dataset
property to access data attributes from the event
object.
The dataset
property provides read and write access to the custom data
attributes of the element.
The property returns a Map
of strings that can be converted to an object.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <button id="btn" data-site="bobbyhadz.com">Click</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', event => { // ๐๏ธ DOMStringMapย {site: 'bobbyhadz.com'} console.log(event.target.dataset); // ๐๏ธ "bobbyhadz.com" console.log(event.target.getAttribute('data-site')); });
We attached a click
event listener to a button.
target
property.We accessed the
dataset
property on the event.target
object to get a Map
of strings that contains
the data attributes of the button element.
const btn = document.getElementById('btn'); btn.addEventListener('click', event => { // ๐๏ธ {bar: 'bobbyhadz.com'} console.log(event.target.dataset); // ๐๏ธ "bobbyhadz.com" console.log(event.target.getAttribute('data-site')); });
Map
of strings containing the custom data attributes of the element.The dataset
property itself is read-only. If you need to update a specific
property, you must access the nested property.
console.log(el.dataset.id); // ๐๏ธ "example" el.dataset.id = 'updated id'; console.log(el.dataset.id); // ๐๏ธ "updated id"
To update the data-site
attribute, access the site
property on the dataset
object and assign a new value to it.
const btn = document.getElementById('btn'); btn.addEventListener('click', event => { console.log(btn.dataset.site); // ๐๏ธ "bobbyhadz.com" btn.dataset.site = 'google.com'; console.log(btn.dataset.site); // ๐๏ธ "google.com" });
If you need to convert the DOM string Map to a native JavaScript object, you can use the spread syntax (...).
const btn = document.getElementById('btn'); btn.addEventListener('click', event => { const map = event.target.dataset; const obj = {...map}; console.log(obj); // ๐๏ธ {site: 'bobbyhadz.com'} });
getAttribute
An alternative approach, which allows you to get any attribute on the DOM element is to call the getAttribute() method on the specific element.
const btn = document.getElementById('btn'); btn.addEventListener('click', event => { const attr = event.target.getAttribute('data-site'); console.log(attr); // ๐๏ธ "bobbyhadz.com" console.log(event.target.getAttribute('id')); // ๐๏ธ "btn" });
getAttribute
method, we have to provide the complete name, including the data-
part.As opposed to when accessing a property on the dataset
map, where the data-
part is excluded.
If the attribute is not found on the DOM element the getAttribute
method will
return null
or an empty string.
You can learn more about the related topics by checking out the following tutorials: