Dofactory.com
Dofactory.com
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

HTML <a> data-* Attribute

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.

Example

#

A custom data-parent attribute on an <a> tag.
Its value is invisible. Click the link to see its value.

Antonio Valdez
<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>

Using data-*

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.


Syntax

<a data-*="value">

Note: The * can be any string, such as data-iddata-costdata-supplier,  etc.


Values

#

Value Description
value A string value. Can be numeric, alphanumeric, JSON, etc.

More Examples

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>

Code explanation

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.


Browser support

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

You may also like

 Back to <a>

Last updated on Sep 30, 2023

Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

Guides