I have a SVG in my document and I add a symbol to it with JavaScript like this:
var myScene =document.getElementById('myScene');
var useSVG = document.createElement('use');
useSVG.setAttribute('xlink:href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);
The symbol does not show up whereas the resulting code is exactly the same as another node written in HTML which is displayed correctly.
Code shown in debugger:
<svg id="myScene" width="200px" height="200px">
<use xlink:href="spriteSheet.svg#mySymbol" x="5" y="50" width="10" height="10"></use>
<!-- this one was in html, it is visible -->
<use xlink:href="spriteSheet.svg#mySymbol" x="10" y="30" width="10" height="10"></use>
<!-- this one is added with javascript. it is not displayed -->
</svg>
SVG works together with HTML, CSS and JavaScript.
createElementNS() Creates an element with the specified namespace URI and qualified name. To create an element without specifying a namespace URI, use the createElement() method.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With