Why is the SVG element created using javascript not showing up?

I have an SVG in my document and I am adding a character to it using javascript:

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 is not displayed, while the resulting code exactly matches another node written in HTML, which is displayed correctly.

Code shown in the 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> 
+5
source share
2 answers

You need to use createElementNS() to create SVG elements. The main createElement() creates elements in the HTML namespace. This way you basically created <html:use> elements instead of <svg:use> .

 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 just realized that there is a second problem with your code. You are using an external link in your href (referring to a character in another file). IE does not seem to support external links.

I found additional information and a possible workaround here: http://css-tricks.com/svg-use-external-source/

+8
source

I'm not 100% sure, but I think you need to set the xlink:href attribute using setAttributeNS() as follows:

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

Also make sure the namespace is declared in 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 problem in the xhtml document, probably this will work for both html5 and stand-alone SVG.

xlink specification

Good luck

+1
source

Source: https://habr.com/ru/post/1203028/


All Articles