HTML <button> data-* Attribute

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

Example

#

A custom data-productid attribute on a button.
The attribute value is not visible, but is readable by JavaScript.

<button data-productid="12247"
        onclick="alert('Product added!');">
  <img src="/img/html/cart.png">&nbsp; Add to Cart
</button>

Using data-*

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

The * part is replaced with a lowercase string, such as data-id, data-type, data-inventory, etc.

A <button> 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 button.


Syntax

<button 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

Four different custom data-* attributes on a <button>.
Clicking the button will display all their values.

<button data-id="49982" 
        data-color="black"
        data-size="9"
        data-product="Nike shoes"
        onclick="addToCart(this);">
          <img src="/img/html/cart.png">&nbsp; Add to Cart  
</button>

<script>
  let addToCart = button => {
    let s = "Id = " + button.getAttribute('data-id') + "\r\n";
    s += "Color = " + button.getAttribute('data-color') + "\r\n";
    s += "Size = " + button.getAttribute('data-size') + "\r\n";
    s += "Product = " + button.getAttribute('data-product');

    alert(s);
  }
</script>

Code explanation

The <button> tag has four data-* attributes.

They are data-id, data-color, data-size, and data-product.

Button clicks are directed to the onclick event.

Onclick invokes a JavaScript function that extracts and displays all four values.


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