简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM