The data-* attribute in HTML5 allows you to store custom data attributes directly in your HTML elements. These attributes provide a way to store extra information that can be used by JavaScript, CSS, or for any other custom data storage purpose.
For example, you might have an element like this:
<div id="user" data-userid="123" data-username="JohnDoe" data-email="[email protected]"></div>
In this case, data-userid, data-username, and data-email
are custom data attributes. You can access and manipulate these attributes using JavaScript:
// Accessing the data attributes using JavaScript
const userDiv = document.getElementById('user');
const userId = userDiv.dataset.userid; // Accessing data-userid attribute
const username = userDiv.dataset.username; // Accessing data-username attribute
const email = userDiv.dataset.email; // Accessing data-email attribute
// Changing the value of a data attribute
userDiv.dataset.username = 'JaneDoe';
These attributes are particularly useful when you want to associate additional data with HTML elements without cluttering the structure with non-standard attributes or data. They are accessible via the dataset
property in JavaScript and can be manipulated or read dynamically.
For styling purposes, you can also use these attributes in CSS:
/* CSS utilizing data attributes */
div[data-userid="123"] {
/* Styles for elements with data-userid="123" */
}
This feature provides a convenient way to store information that might be useful for scripting, styling, or other custom functionalities associated with HTML elements.