[Solved] how to insert a svg tag inside a inner g tag


In your source code there are two main problems:

  1. You use the same id value many times. According to HTML documentation the id is used as unique identificator for an element.
  2. You are “attaching” the circle to <svg> and not to <g> tag with the svg.appendChild(shape);

You can do something similar to:

var svgElem = document.createElementNS("http://www.w3.org/2000/svg", "svg"); //create <svg>
var g = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create <g>
g.classList.add("myClass");
svgElem.appendChild(g); //append <g> inside <svg>

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); //create <circle>
g.appendChild(circle); //append <circle> inside <g>

var g_2 = document.createElementNS("http://www.w3.org/2000/svg", "g"); //create another <g>
g_2.classList.add("myClass");
svgElem.appendChild(g_2); //append <g> inside <svg>


var coll = svgElem.getElementsByClassName("myClass"); //coll contains HTMLCollection

/* You cannot use coll.appendChild(circle);*/

coll[0].appendChild(circle); //append <circle> to the first <g> returned by getElementsByClassName("myClass");

12

solved how to insert a svg tag inside a inner g tag