Retrieving Data Attributes in JavaScript Code
To access attributes beginning with "data-" in JavaScript code for the provided HTML element, you'll need to utilize the dataset property, as demonstrated in the code below:
<code class="js">document.getElementById("the-span").addEventListener("click", function() { var json = JSON.stringify({ id: parseInt(this.dataset.typeid), // Accessing data-typedId attribute subject: this.dataset.type, // Accessing data-type attribute points: parseInt(this.dataset.points), // Accessing data-points attribute user: "H. Pauwelyn" }); });</code>
After executing this code, the json variable will contain an object with the following values:
{ "id": 123, "subject": "topic", "points": -1, "user": "H. Pauwelyn" }
This technique allows you to conveniently access and utilize data attributes in JavaScript code, simplifying the management and manipulation of custom attributes in your HTML markup.
The above is the detailed content of How to Access and Use Data Attributes in JavaScript Code?. For more information, please follow other related articles on the PHP Chinese website!