HTML <label> data-* Attribute

The data-* attribute on a <label> tag attaches additional data to the label. To create a custom attribute, replace the * with a lowercase string, such as data-id, data-status, or data-location.

Example

#

A custom data-order attribute on a <label>.
The attribute value is not visible, but it is readable by JavaScript.


<form>
  <label for="firstname" data-order="1">First Name</label><br />
  <input type="text" id="firstname" name="firstname">
</form>

Using data-*

The data-* attribute adds custom information to a <label> element.

The * part is replaced with a lowercase string, such as data-id, data-cost, or data-location.

An <label> 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 label.


Syntax

<label 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-binding attribute on a <label> tag.
Clicking the button will display the binding value.



<form>
  <label id="mylabel" for="firstname" data-binding="Customer first name">First Name</label><br />
  <input type="text" id="firstname" name="firstname">
</form>

<br/>
<button onclick="show();">Show data</button>

<script>
  let show = () => {
    let element = document.getElementById("mylabel");
    alert("Label for = " + element.getAttribute('data-binding'));
  }
</script>

Code explanation

The <label> tag has a custom data-for attribute.

The data-for attribute stores what type of data the label is used for.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the label purpose.

Note: Notice how the label purpose displays immediately without server call.


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 <label>
Guides