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

What I am trying to do: insert an svg into a inner most g tag

Below is my code

    let svg = document.querySelector('svg');
    let g = svg.getElementsByClassName('srd-default-link');

    let shape = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
    shape.id = 'circle';
    shape.setAttribute('cx', 25);
    shape.setAttribute('cy', 25);
    shape.setAttribute('r', 20);
    shape.setAttribute('style', 'fill: green');

     g[0].appendChild(shape);

The result: only able to insert it in the first layer g tag and not the inner most g tag

Any advice is appreciated



Solution 1:[1]

My own solution, I put a if condition,

if (g.length !== 0) g[0].appendChild(shape);

and I put it in componentDidUpdate at the first line. Thanks @Wolfetto for helping in the initial part. I will leave it here for anyone who needs it in the future.

if (g.length !== 0) {
        for (let i = 0; i < g[0].childNodes.length; i++) {
            let item = g[0].childNodes[i];
            if (item.nodeName === 'g') item.appendChild(shape);
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1