mpsg
mpsg

Reputation: 193

how to insert svg element into group with javascript

I have some SVG code embedded in HTML and I need to add several polygons to the existing SVG with javascript. The problem is that the SVG that exists (that I am adding to) is in a group (g tag) and because of layering, I need to add the new polygons to specific places in that group. I've been writing javascript for a few years now, but I am just starting to learn SVG and I don't know how to add elements to a specific place in the SVG DOM with javascript. My comment below explains why this is different than a previously asked question.

For example:

<g id="group1">
    <rect x="20" y="50" width="700" height="20" fill="url(#grad1)"/>
    I need to add polygons here.
    <rect x="20" y="140" width="700" height="20" fill="url(#grad1)"/>
</g>

Upvotes: 2

Views: 2420

Answers (1)

maowtm
maowtm

Reputation: 2012

Use Node.insertBefore:

var insertedNode = parentNode.insertBefore(newNode, referenceNode);

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

Upvotes: 2

Related Questions