Reputation: 7641
I used this code to generate and append an svg element a DOM element.
var svg_el = document.createElement("svg");
svg_el.className = "symbol";
var use_el = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use_el.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#my-symbol-icon');
// use_el.setAttribute('href', '#exp-col-icon'); // tried also this
svg_el.appendChild(use_el)
var element = document.getElementById("myElement");
element.appendChild(svg_el)
This is how I see my svg element when I inspect my web page, however it's not visually there.
<div id="myElement"><svg class="symbol"><use xlink:href="#my-symbol-icon"></use></svg></div>
If I add the same exact code manually, it works visually as expected, but I need to make it work with JavaScript.
Upvotes: 1
Views: 543
Reputation: 7641
This made svg element be shown with no problems.
var svg_el = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg_el.setAttribute('class',"symbol");
var use_el = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use_el.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#my-symbol-icon');
var element = document.getElementById("myElement");
element.appendChild(svg_el)
I don't know exactly why this works, while the code in question seems that it should work.
Upvotes: 2