0

In my chrome extension, I am trying to display an SVG sprite, yet it is not displaying the content. I am not seeing any errors in the console and have tried both local and online. I have also tried using an IMG tag to no avail. All other advice I have found talks about constructing the shapes.

var svg = div.appendChild(document.createElement( "svg" ));
    svg .classList.add( "actionButtonImage" );
var use = svg.appendChild(document.createElement( "use" ));
    use .setAttribute( "xmlns:xlink"," http://www.w3.org/1999/xlink" );
    use .setAttribute( "xlink:href",   href );

EDIT: I am not looking to make the vectors in page, I am using external SVG sprites! And have spen a day and half researching this!


So far I have this to no avail

var svg = div.appendChild(document.createElementNS( "http://www.w3.org/2000/svg", "svg" ));
    svg .classList.add("actionButtonImage");
var use = svg.appendChild(document.createElementNS( "http://www.w3.org/1999/xlink", "use"   ));
    use .setAttributeNS("http://www.w3.org/1999/xlink","href",href);
Jason
  • 779
  • 1
  • 9
  • 30
  • You could create a img tag and reference the src as the svg source at that would work. You would also need to append it to the extension –  Feb 08 '17 at 22:41
  • 1
    Possible duplicate of [Creating SVG elements dynamically with javascript inside HTML](http://stackoverflow.com/questions/20539196/creating-svg-elements-dynamically-with-javascript-inside-html) – Makyen Feb 08 '17 at 22:47
  • 1
    use is not an element in the xlink namespace, it's in the svg namespace. It's href attribute is in the xlink namespace though (you have that bit correct). – Robert Longson Feb 09 '17 at 00:16

1 Answers1

4

You can't create SVG elements with createElement, you need createElementNS and to provide the SVG namespace.

Similarly you can't use setAttribute to set an attribute in the xlink namespace, you can only create attributes in the null namespace. You'd need to use setAttributeNS to set attributes in the xlink namespace.

Finally xmlns:xlink is not a real attribute, it's created by serialisers as a side effect of attributes and elements being correctly created in namespaces so you should not need to use setAttribute to create it.

Robert Longson
  • 118,664
  • 26
  • 252
  • 242