0

I am new to Javascript and SVG. Hope you guys can help me. I created a function addEltToSVG()

function addEltToSVG(svg, name, attrs) {
    
    var element = document.createElementNS("http://www.w3.org/2000/svg", name);
    if (attrs === undefined) attrs = {};
    for (var key in attrs) {
        element.setAttributeNS(null, key, attrs[key]); // namespace = null, name = key, value = attrs[key]
    }
    if (name == "text") {
        var textNode = document.createTextNode(attrs['content']);
        element.appendChild(textNode);
    }
    svg.appendChild(element); // insert elements to the svg 
}

Then, I used this function like this. And it doesn't show up anything. I searched for solutions but it still doesn't work.

var width = 600, height = 400;

var s = document.createElementNS("http://www.w3.org/2000/svg", 'svg'), chartID = "histogram";
s.setAttribute("width", width);
s.setAttribute("height", height);

var rect1 = addEltToSVG(s, "rect", {
  "width": 50,
  "height": 10,
  "fill": "red"
});
  • have you appended the svg element (s) to the DOM? – enxaneta Mar 15 '21 at 17:55
  • Are you simply updating an SVG already loaded in the DOM? A known issue, the SVG needs to be 'redrawn' https://stackoverflow.com/questions/5966385/update-svg-dynamically -- it's simpler to remove and add the updated the SVG – franklylately Mar 15 '21 at 18:13

1 Answers1

0

I believe rect1 returning undefined is your issue. You don't seem to be returning anything from the function

    function addEltToSVG(svg, name, attrs) {
      var element = document.createElementNS("http://www.w3.org/2000/svg", name);
      if (attrs === undefined) attrs = {};
      for (var key in attrs) {
        element.setAttributeNS(null, key, attrs[key]); // namespace = null, name = key, value = attrs[key]
       }
       if (name == "text") {
          var textNode = document.createTextNode(attrs['content']);
          element.appendChild(textNode);
        }
       svg.appendChild(element);
       return svg;
     }

    var width = 600, height = 400;

    var s = document.createElementNS("http://www.w3.org/2000/svg", 'svg'), chartID = "histogram";
    s.setAttribute("width", width);
    s.setAttribute("height", height);

    var rect1 = addEltToSVG(s, "rect", {
      "width": 50,
      "height": 10,
      "fill": "red"
    });
console.log(rect1);
Vinu Prasad
  • 928
  • 5
  • 12