user2181397 user2181397 - 3 months ago 15
Javascript Question

Not able to create svg

I am trying to create a

svg
,
polyline
using javascript.

Though it is rightly creating & appending the elements but the
polyline
is not drawing on the screen.

var _button = document.createElement('button');
_button.id = "scrollToTop";
_button.class = "";

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('style', 'border: 1px solid black');
svg.setAttribute('width', '600');
svg.setAttribute('height', '250');
svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

var _polyline = document.createElement('polyline');
_polyline.setAttribute("fill", "#006600");
_polyline.setAttribute("stroke", "#FFFFFF");
_polyline.setAttribute('stroke-width', '1');
_polyline.setAttribute('stroke-linecap', 'round');
_polyline.setAttribute('stroke-linejoin', 'round');
_polyline.setAttribute("points", "10,52 60,52 35,0");

document.getElementById('scrollToTop').appendChild(svg).appendChild(_polyline);


Please help to resolve this problem

JSFIDDLE

Answer

You just forgot the namespace:

var _polyline = document.createElementNS("http://www.w3.org/2000/svg", 'polyline');
_polyline.setAttribute("fill", "#006600");
_polyline.setAttribute("stroke", "#FFFFFF");
_polyline.setAttribute('stroke-width', '1');
_polyline.setAttribute('stroke-linecap', 'round');
_polyline.setAttribute('stroke-linejoin', 'round');
_polyline.setAttribute("points", "10,52  60,52  35,0");

Here is your working code:

var _button = document.createElement('button');
    _button.id = "scrollToTop";
    _button.class = "";

    var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '600');
    svg.setAttribute('height', '250');
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

    var _polyline = document.createElementNS("http://www.w3.org/2000/svg", 'polyline');
    _polyline.setAttribute("fill", "#006600");
    _polyline.setAttribute("stroke", "#FFFFFF");
    _polyline.setAttribute('stroke-width', '1');
    _polyline.setAttribute('stroke-linecap', 'round');
    _polyline.setAttribute('stroke-linejoin', 'round');
    _polyline.setAttribute("points", "10,52  60,52  35,0");

document.getElementById('scrollToTop').appendChild(svg).appendChild(_polyline);
<div id="scrollToTop"></div>