Why SVG use element created with JavaScript is not shown?

I am not sure to 100% but I think you need to set the xlink:href Attribute using setAttributeNS() like this:

useSVG.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'spriteSheet.svg#mySymbol');

Also make sure that the namespace is declared within your document.

<html xmlns:xlink="http://www.w3.org/1999/xlink">

<!-- or if standalone svg -->

<svg xmlns:xlink="http://www.w3.org/1999/xlink">

However, this way I solved the same issue within an xhtml document, probably that will work for html5 or standalone SVG, too.

xlink specification

good luck!


You need to use createElementNS() to create SVG elements. The basic createElement() creates elements in the HTML namespace. So you basically have been creating <html:use> elements instead of <svg:use> ones.

var myScene =document.getElementById('myScene');
var useSVG = document.createElementNS('http://www.w3.org/2000/svg', 'use');
useSVG.setAttributeNS('http://www.w3.org/1999/xlink','href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);

Demo here

Update

I have just realised there is a second problem with your code. You are using an external reference in your href (it's referenceing a symbol in another file). It seems IE doesn't support external references.

I found more info, and a possible workaround, here: http://css-tricks.com/svg-use-external-source/

Tags:

Javascript

Svg