HTML Data Attributes (Live Playground)
In this tutorial, we will learn how to use custom HTML data attributes to store and access data related to specific elements on your web pages. Data attributes provide an easy way to store extra information that is not part of the standard HTML attributes.
What are Data Attributes?
HTML data attributes are custom attributes that you can add to HTML elements to store additional information. These attributes are prefixed with data-
and can be accessed and manipulated using JavaScript or CSS.
Adding Data Attributes
To add a data attribute to an element, use the data-
prefix followed by the attribute name. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Data Attributes</title>
</head>
<body>
<div id="user" data-name="John Doe" data-age="30">Welcome!</div>
</body>
</html>
In this example, we added two data attributes (data-name
and data-age
) to the <div>
element.
Accessing Data Attributes using JavaScript
You can access data attributes using JavaScript's dataset
property. Here's how to do it:
<!DOCTYPE html>
<html>
<head>
<title>Data Attributes</title>
<script>
function showData() {
const userDiv = document.getElementById('user');
const userName = userDiv.dataset.name;
const userAge = userDiv.dataset.age;
console.log(`Name: ${userName}, Age: ${userAge}`);
}
</script>
</head>
<body>
<div id="user" data-name="John Doe" data-age="30">Welcome!</div>
<button onclick="showData()">Show user data</button>
</body>
</html>
In this example, we created a function called showData()
that retrieves the data
attributes from the <div>
element and logs them in console when the button is clicked.
Accessing Data Attributes using CSS
You can also access data attributes using CSS by using the attr()
function. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Data Attributes</title>
<style>
#user::after {
content: ' (' attr(data-name) ', ' attr(data-age) ' years old)';
}
</style>
</head>
<body>
<div id="user" data-name="John Doe" data-age="30">Welcome</div>
</body>
</html>
In this example, we used CSS to access the data attributes and display them after the content of the <div>
element.
Conclusion
Now you know how to use HTML data attributes to store and access additional information related to specific elements on your web pages. This can be useful for various purposes, such as storing user data, metadata, or additional styling information.