Dofactory.com
Dofactory.com
Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

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.

Example

#

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

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.


Syntax

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

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

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

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:

Chrome
4.0 Jan 2010
Firefox
3.0 Jun 2008
IE/Edge
9.0 Mar 2011
Opera
10.1 Jun 2010
Safari
3.2 Nov 2008

You may also like

 Back to <svg>

Last updated on Sep 30, 2023

Earn income with your HTML skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest freelancing marketplace for people like you.
By adding your name & email you agree to our terms, privacy and cookie policies.

Guides