How to get data attribute JavaScript
By FoxLearn 10/4/2024 1:40:11 AM 121
The dataset
property in JavaScript provides a way to access an HTML element's data attributes as a DOMStringMap object. This simplifies the process of retrieving, modifying, and interacting with custom data stored in attributes such as data-id
or data-name
.
For example:
<div id="el1" data-user-id="12345" data-role="admin"> User Info </div>
To access the data attributes, you can use the following code.
// Get the element by its Id const element = document.getElementById('el1'); // Access the data attributes const userId = element.dataset.userId; // "12345" const role = element.dataset.role; // "admin"
When accessing data attributes via dataset
, the attribute name is camel-cased.
For example, data-user-id
becomes userId
.
The values retrieved from dataset
are strings. You may need to convert them to other types (e.g., numbers) if necessary.
You can also set data attributes in a similar way.
// Set a new data attribute element.dataset.newAttribute = 'new value';
You can also use .getAttribute() method to get data attribute JavaScript.
The .getAttribute()
method in JavaScript retrieves the value of a specified attribute from an HTML element. To access data attributes, you can use element.getAttribute('data-attribute')
. This method allows for precise selection and manipulation of individual data attributes without needing to access all of them at once.
For example:
<span id="123" data-name="name" data-point="5"> FoxLearn </span>
let input = document.getElementById('123'); const point = parseInt(input.getAttribute('data-point');
This method provides a clean and efficient way to work with custom data attributes in your HTML elements!