Dofactory.com
Dofactory.com

HTML <img> data-* Attribute

A data-* attribute on an <img> tag attaches additional data to the image.

To create a custom attribute, replace * with a lowercase string, such as data-id, data-status, or data-location.

Example

#

A custom data-price attribute on an <img>.
The attribute value is not visible, but it is readable by JavaScript.

<img src="/img/html/vangogh.jpg"
     data-price="60 million USD">

Using data-*

The data-* attribute allows you to add custom attributes to a <img> element.

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

An <img> element can have any number of data-* attributes, each with their own name.

These attributes usually store additional data about the img (e.g. id, options, variations, etc.).

Using data-* attributes reduces the need for Ajax requests to the server.

Note: The data-* attribute does not change the appearance of the img tag in any way.


Syntax

<img 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-topic attribute on an <img> element.
Clicking the button will display the topic value.



<img id="myimg"
     src="/img/html/vangogh.jpg"
     data-topic="Van Gogh self-portrait">

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

<script>
  let show = () => {
    let element = document.getElementById("myimg");
    alert("Topic = " + element.getAttribute('data-topic'));
  }
</script>

Code explanation

The <img> tag below contains the data-topic attribute.

The data-topic attribute specifies the topic of the <img>.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the image topic.

Note: Notice how the title will 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 <img>

Author: Jack Poorte
Published: Jun 20 2021
Last Reviewed: Sep 30 2023


Quick question: what's your favorite/least favorite part of Dofactory?


Guides