How to access html data attributes in JavaScript
How to get and set data attributes on HTML elements with JavaScript.
There are times when you need to access data from DOM elements. You can attach
the data to any attribute name you want but using the data-
prefix will yield
some additional functionality that can be quite powerful.
<div class="person" data-first-name="John">…</div>
Getting Data Attributes on HTML Nodes
You can access a special JavaScript object on any html node called dataset
This object represents the attributes on the HTML element that are prefixed with
data-
Data attributes are stripped of the data-
prefix and added to the dataset
object.
<div class="person" data-first-name="John" data-last-name="Smith">…</div>
const person = document.querySelector(".person")
console.log(person.dataset)
// { firstName: 'John', lastName: 'Smith' }
Note: Data values are stored and retrieved as strings.
Depending on how the data attribute is named will depend on how it is set to the dataset object:
- kebab-case
data-first-name
→dataset.firstName
- camelCase
data-lastName
→dataset.lastname
- snake_case
data-middle_name
→dataset.middle_name
Setting Data Attributes in JavaScript
Adding values to the dataset object will result on their respective attributes on the html node.
<div class="animal">...</div>
const animal = document.querySelector(".animal")
animal.dataset.type = "lion"
Result:
<div class="animal" data-type="lion">...</div>
Summary
Accessing and setting data attributes is a powerful technique to manage data between the DOM and JavaScript.
Have some feedback on this post? .