Custom Data Attributes
allow us to
attach
custom
data
to
HTML elements
without affecting the element's functionality or appearance.
Syntax:
To create a custom data attribute, you need to use the data- prefix followed by your chosen attribute name.
Example:
<div data-info="example-data" data-count="42">Custom Data Attributes</div>
In this example, we have added two custom data attributes, data-info and data-count, to a <div> element.
Accessing Data Attributes with JavaScript:
<div id="myDiv" data-info="example-data" data-count="42">Custom Data Attributes</div>
<script>
const myDiv = document.getElementById("myDiv");
// Accessing individual data attributes
const infoData = myDiv.dataset.info;
const countData = myDiv.dataset.count;
console.log(infoData); // Output: "example-data"
console.log(countData); // Output: "42"
</script>
Modify:
<div id="myDiv" data-info="example-data" data-count="42">Custom Data Attributes</div>
<script>
const myDiv = document.getElementById("myDiv");
// Modifying data attributes
myDiv.dataset.info = "new-data";
myDiv.dataset.count = 100;
</script>
Using Custom Data Attributes with Events:
<button data-action="delete" data-id="123">Delete Item</button>
<script>
const deleteButton = document.querySelector("[data-action='delete']");
deleteButton.addEventListener("click", function(event) {
const itemId = event.target.dataset.id;
console.log("Deleting item with ID:", itemId);
// Perform the delete operation using the itemId
});
</script>