Custom data can be stored in DOM elements to associate additional information with HTML elements. JavaScript provides native HTML data-* attributes for this purpose, while jQuery provides the .data() method to attach and retrieve data from selected elements.
- Use data-* attributes to store custom data directly in HTML elements.
- Access stored data using JavaScript methods such as getAttribute() or the dataset property.
- Use the jQuery .data() method to store and retrieve data associated with DOM elements.
Approach 1: Using HTML data-* Attributes
HTML data-* attributes allow you to store custom data directly on an element. Every custom data attribute must begin with data-.
Syntax:
<div data-name="value"></div>The data can be accessed using JavaScript when required.
Example: This example stores a discount value using a data-* attribute and displays it when the button is clicked.
<!DOCTYPE html>
<html>
<body>
<div>
<h4>Data Structures and Algorithms</h4>
<button onclick="showDetails(this)"
data-discount="60%">
Click Here for Discount
</button>
</div>
<br>
<div>
<h4>Operating System</h4>
<button onclick="showDetails(this)"
data-discount="40%">
Click Here for Discount
</button>
</div>
<script>
function showDetails(element) {
const discount =
element.getAttribute("data-discount");
alert(discount);
}
</script>
</body>
</html>
Output:
Approach 2: Using the dataset Property
The JavaScript dataset property provides a convenient way to access custom data-* attributes. The attribute name is converted to camelCase when accessed through dataset.
Example: This example retrieves custom data from an element and displays it when the button is clicked.
<!DOCTYPE html>
<html>
<body>
<button id="course"
data-name="JavaScript"
data-level="Beginner">
Show Details
</button>
<p id="output"></p>
<script>
const button =
document.getElementById("course");
const output =
document.getElementById("output");
button.addEventListener("click", function () {
output.textContent =
"Course: " + button.dataset.name +
", Level: " + button.dataset.level;
});
</script>
</body>
</html>
Output: