A data-* attribute on an <a> tag attaches additional data to the anchor element.
To create a custom attribute, replace * with a lowercase string, such as data-id
, data-status
, or data-location
.
A custom data-parent
attribute on an <a> tag.
Its value is invisible. Click the link to see its value.
<a data-parent="Sophie Valdez" id="myanchor"
href="javascript:parent()">Antonio Valdez</a>
<script>
let parent = () => {
let element = document.getElementById('myanchor');
alert("Parent = " + element.getAttribute('data-parent'));
}
</script>
The data-* attribute adds custom information to an <a> element.
The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.
An <a> 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 link.
<a 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-country
attribute on each of the four <anchor> tags.
Clicking a city will display its country value.
<nav>
<a data-country="Netherlands" onclick="show(this);" href="#null">Amsterdam</a> <br />
<a data-country="Belgium" onclick="show(this);" href="#null">Brussels</a> <br />
<a data-country="France" onclick="show(this);" href="#null">Paris</a> <br />
<a data-country="Spain" onclick="show(this);" href="#null">Madrid</a> <br />
</nav>
<script>
let show = element => {
alert("Country = " + element.getAttribute('data-country'));
}
</script>
Four links are created with <a> tags.
Each has a custom data-country
attribute with a country name.
Clicks are handled by the onclick
event.
Onclick invokes a JavaScript function that extracts and displays the country.
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 <a>