Create »svg« and »use« element with JavaScript

Creating SVG elements dynamically via JavaScript is not as easy as I thought… In this post, I show how to create an SVG element with JS, that displays a symbol via a use element.

Preliminary remark

SVG elements can be displayed like that (there are more possibilities to display an SVG):

<svg> <use xlink:href="#down-arrow"></use> </svg>
Code language: HTML, XML (xml)

There we reference an SVG element we want to show via the use element (these three lines are the markup we want to create with JavaScript). In my concrete case, the above markup displays an arrow pointing to the bottom, that is included into the page with the following markup:

<svg xmlns="" xmlns:xlink="" id="hannover-svg-icons"> <symbol viewBox="0 0 16 16" id="down-arrow"> <polygon points="11,6 7.5,9.5 4,6 3,7 7.5,11.5 12,7"></polygon> </symbol> </svg>
Code language: HTML, XML (xml)

The id of the symbol element is the same as the value for xlink:href.

The creation with JavaScript

If you know what to look for, it is not that hard. This is the complete code:

var svgElem = document.createElementNS('', 'svg'), useElem = document.createElementNS('', 'use'); useElem.setAttributeNS('', 'xlink:href', '#down-arrow'); svgElem.appendChild(useElem);
Code language: JavaScript (javascript)

It is important to know that you have to use document.createElementNS with the correct namespace to create the svg and use element – it does not work with document.createElement. Likewise, the setAttributeNS method must be used for the xlink:href attribute instead of setAttribute – again with the correct Namespace.

After this code was run, svgElem contains the SVG element with use that can be used on the site.

5 reactions on »Create »svg« and »use« element with JavaScript«

  1. But what if your "down-arrow" would have class="my-style", and .my-style - is already on the page. Whould the style be applyed to the newly created useElem?


Leave a Reply

Your email address will not be published. Required fields are marked *