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.



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

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.


<button data-*="value" >

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



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-product="Nike shoes"
          <img src="/img/html/cart.png">&nbsp; Add to Cart  

  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');


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:

1.0 Sep 2008
1.0 Sep 2002
1.0 Aug 1995
1.0 Jan 2006
1.0 Jan 2003

You may also like

 Back to <button>