A data-* attribute on a <div> tag attaches additional data to the div element.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-registration-number
attribute on a <div>.
The attribute value is not visible, but it is readable by JavaScript.
We will email your entry passes to the Louvre Museum in Paris.
<div data-registration-number="40039"
style="background-color:aliceblue;padding:25px;">
<b>Registration Successful!</b>
<p>We will email your entry passes to the Louvre Museum in Paris.</p>
</div>
The data-* attribute adds custom information to a <div> element.
The * part is replaced with a lowercase string, such as data-id, data-source, data-category, etc.
An <div> element can have any number of data-* attributes, each with their own name.
Using data-* attributes reduces the need for requests to the server.
Note: The data-* attribute is not visible and does not change the appearance of the div element.
<div data-*="value" >
Note: The * can be any string, such as data-id
, data-cost
, data-supplier
, etc.
Value | Description |
---|---|
value | A string value. Can be numeric, alphanumeric, JSON, etc. |
A custom data-ticket
attribute on a <div> element.
Clicking the button will display the ticket number.
We will email your entry passes to the Louvre Museum in Paris.
<div data-ticket="1223887" id="mydiv"
style="background-color:aliceblue;padding:25px;">
<b>Registration Successful!</b>
<p>We will email your entry passes to the Louvre Museum in Paris.</p>
</div>
<br/>
<button onclick="show();">Show data</button>
<script>
let show = () => {
let element = document.getElementById("mydiv");
alert("Ticket # = " + element.getAttribute('data-ticket'));
}
</script>
The <div> tag has a custom data-ticket
attribute.
The data-ticket
attribute holds the ticket number.
Clicks are handled by the onclick
event.
Onclick invokes a JavaScript function that extracts and displays the ticket number.
Note: Notice how the number displays quickly without the need for a server call.
Here is when data-* support started for each browser:
Chrome
|
1.0 | Sep 2008 |
Firefox
|
1.0 | Sep 2002 |
IE/Edge
|
1.0 | Aug 1995 |
Opera
|
1.0 | Jan 2006 |
Safari
|
1.0 | Jan 2003 |
Back to <div>