TIL accessing different data attributes
POSTED ON:
TAGS: javascript data html
Say you had data you wanted to store on a element.
<div id="lunch" data-sandwich="tuna" data-drink="soda" data-side="chips" data-snack="cookie" data-payment-method="credit card">
Lunch!
</div>
To use it, you can use:
const lunchElement = document.getElementById('lunch');
const lunchSandwich = lunchElement.getAttribute('data-sandwich');
console.log(lunchSandwich); // Output: "tuna"
But that's a lot of data you have to pass for data-drink
, data-side
, data-snack
, and data-payment-method
.
A better way is to go with the Element.dataset
property.
let lunch = document.querySelector('#lunch');
let data = lunch.dataset;
let data = {
drink: 'soda',
paymentMethod: 'credit card',
sandwich: 'tuna',
side: 'chips',
snack: 'cookie'
};
via Managing data attributes with the dataset property in vanilla JavaScript
Related TILs
Tagged: javascript