HTML <svg> data-* Attribute

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

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



A custom data-shape attribute on an <svg> image.
The attribute value is not visible, but is readable by JavaScript.

<svg data-shape="Rectangle" width="300" height="100">
  <rect width="300" height="100" fill="orangered" />

Using data-*

The data-* attribute adds custom information to an <svg> element.

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

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


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

A custom data-subject attribute on an <svg> element.
Clicking the button will display the subject value.

<svg id="mysvg" data-subject="Simple rectangle" width="300" height="100">
  <rect width="300" height="100" fill="orangered" />

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

  let toggle = () => {
    let element = document.getElementById("mysvg");
    alert("Subject = " + element.getAttribute('data-subject'));

Code explanation

The <svg> tag has a custom data-subject attribute.

The shape of the svg is stored in the data-subject.

Clicks are handled by the onclick event.

Onclick invokes a JavaScript function that extracts and displays the <svg> subject.

Note: Notice how the shape displays immediately without server call.

Browser support

Here is when data-* support started for each browser:

4.0 Jan 2010
3.0 Jun 2008
9.0 Mar 2011
10.1 Jun 2010
3.2 Nov 2008

You may also like

 Back to <svg>

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

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