Home >Web Front-end >HTML Tutorial >How to store custom data in HTML as private data for the page or application?
Custom attributes are specially designed attributes that are not included in the standard HTML5 attributes. They allow us to customize HTML tags by adding our own data.
A custom attribute is any attribute that starts with data-. We can embed custom attributes on all HTML components using data-* attributes.
In HTML, the syntax of data-* attributes is relatively simple. Every element starting with data- is a data-* attribute.
<sample_data> id = “sample” data-index = 1 data-row = 23 data-column = 44 </sample_data>
Accessing these data properties using JavaScript is also relatively simple. We can use getAttribute() with its full HTML name, which can be read using the dataset attribute.
const article = document.querySelector('#sample'); sample_data.dataset.index; sample_data.dataset.row; sample_data.dataset.column;
Use the CSS attr() function to access data.
sample_data::before { content: attr(data-index); }
The following are examples...
The Chinese translation ofIn the following example, we use JavaScript to read the value of the attribute.
<!DOCTYPE html> <html> <body> <h1>Result</h1> <ul> <li onclick="showPosition(this)" id="Siddarth" data-position="winner"> Siddarth </li> <li onclick="showPosition(this)" id="Arjun" data-position="runner up"> Arjun </li> <li onclick="showPosition(this)" id="Badri" data-position="third"> Badri </li> <li onclick="showPosition(this)" id="Nanda" data-position="lost"> Nanda </li> </ul> <script> function showPosition(runner) { var position = runner.getAttribute("data-position"); alert("The " + runner.innerHTML + " is " + position + "."); } </script> </body> </html>
When the above script is executed, it will generate an output of a list of names containing some data.
When you try to click on any of the names, the function gets the data and displays an alert box showing the custom data we used.
The above is the detailed content of How to store custom data in HTML as private data for the page or application?. For more information, please follow other related articles on the PHP Chinese website!