Chen Eshchar Chen Eshchar - 1 year ago 120
HTML Question

SVG with USE tag not rendering

DOM already includes empty SVG tag ("svg") when I try to dinamically append a USE tag of an existing SVG symbol ("symbol") with an id ("iconId"):

svg[0].setAttribute('viewBox', symbol.getAttribute('viewBox'));
svg.append('<use xlink:href="#' + iconId + '"></use>');

Now, this doesn't render the SVG. In Chrome, it renders if I add


or manually manipulate the viewBox attribute, but that's not a real solution and IE doesn't like it at all.
It worths mentioning that if I append SVG graphics directly, the element renders.

What is happening here and why isn't the SVG drawing after appending the USE tag?

Answer Source

After all it was indeed a matter of namespaces.

Specifically, SVG elements and attributes must be created and set using document.createElementNS and node.setAttributeNS.

$(document).ready(function(evt) { 
  var svgns = '',
      xlinkns = '',
      use = document.createElementNS(svgns, 'use');
  use.setAttributeNS(xlinkns, 'xlink:href', '#save');
#svgStore { 
  display: none;  

#useSVG {
  width: 16px;
  height: 16px;
<script src=""></script>

<svg style="display:none;" id="svgStore" style="display: none;" xmlns="" xmlns:xlink="">
    <symbol viewBox="0 0 16 16" id="save"><title>save</title>       <g id="svgstore3748a955346b4a088bbdc55a22f56504_x31_6_13_"> 
        <path style="fill-rule:evenodd;clip-rule:evenodd;" d="M9,4h2V2H9V4z M13,13H3v1h10V13z M13,11H3v1h10V11z M13,0H0v16h16V3L13,0z
		 M3,1h9v4H3V1z M14,15H2V8h12V15z M13,9H3v1h10V9z">
SVG use:
<svg id="useSVG" xmlns=""></svg>

Thanks to @RobertLongson and for directing to the answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download