HTML <svg> id Attribute

The id attribute on an <svg> tag assigns an identifier to the svg (scalable vector graphics) element. The identifier must be unique across the page.

Example

#

An id attribute on a <svg> element.

<svg id="circle-svg" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="steelblue" 
          stroke-width="2" fill="lightblue" />
</svg>

Using id

The id attribute assigns an identifier to the <svg> element.

The identifier must be unique across the page.

The id allows programmatic access to the <svg> element.

Tip:  id is a global attribute that can be applied to any HTML element.


Syntax

<svg id="identifier" />

Values

#

Value Description
identifier A unique alphanumeric string. The id value must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (-), underscores (_), colons (:), and periods (.).

More Examples

An <svg> element with a unique id attribute.
Clicking the button displays the content of the element.



<svg id="mysvg" width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="steelblue" 
          stroke-width="2" fill="lightblue" />
</svg>

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

<script>
  let show = () => {
     let element = document.getElementById("mysvg");
     alert("Content = " + element.innerHTML);
  }
</script>

Code explanation

The id attribute assigns a unique identifier for the <svg>.

Clicking the button calls JavaScript which locates the <svg> using the id.

Finally, the content of the <svg> element is displayed in an alert box.


Browser support

Here is when id 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>
Guides