As a web developer, you may have encountered instances where you need to get the value of a data attribute, such as data-id, in JavaScript.
The data-id attribute is used to store custom data private to the page or application, and can be retrieved using JavaScript for various purposes such as manipulating the element or sending the data to the server.
In this Javascript tutorial, we will explore how to retrieve the data-id attribute using JavaScript.
The dataset Property
The most straightforward way to retrieve the data-id attribute is by using the dataset
property.
The dataset
property is an object that provides access to all custom data attributes (data-*) set on an element.
It is supported in modern browsers such as Google Chrome, Mozilla Firefox, and Microsoft Edge.
Here’s how to retrieve the data-id attribute using the dataset
property:
let element = document.querySelector("#my-element"); let dataId = element.dataset.id; console.log(dataId);
In the code above, element
is a reference to the element whose data-id attribute we want to retrieve.
The dataset.id
property returns the value of the data-id attribute.
In this case, it will log the value of the data-id attribute in the console.
The getAttribute() Method
Another way to retrieve the data-id attribute is by using the getAttribute()
method.
The getAttribute()
method is a method of the Element interface and is supported in all modern browsers.
Here’s how to retrieve the data-id attribute using the getAttribute()
method:
let element = document.querySelector("#my-element"); let dataId = element.getAttribute("data-id"); console.log(dataId);
In the code above, element
is a reference to the element whose data-id attribute we want to retrieve.
The getAttribute("data-id")
method returns the value of the data-id attribute.
In this case, it will log the value of the data-id attribute in the console.
Conclusion
In this tutorial, we have explored two ways to retrieve the data-id attribute in JavaScript using the dataset
property and the getAttribute()
method.
Both methods are easy to use and supported by modern browsers.
Choose the one that best suits your needs and start retrieving custom data attributes in your web applications today.