Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SVG use element created with JavaScript is not shown?

Tags:

javascript

svg

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>
like image 700
bokan Avatar asked Sep 20 '14 08:09

bokan


People also ask

Does SVG use JavaScript?

SVG works together with HTML, CSS and JavaScript.

What is createElementNS in JS?

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.


1 Answers

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/

like image 199
Paul LeBeau Avatar answered Sep 24 '22 08:09

Paul LeBeau