score:0

edit: If you want to append new groups of rect/text, make your first selection the svg container.

Using the number of children as index for repositioning groups vertically, otherwise they overlap.

function myFunction(clicked_id) {   
   const svg = d3.select('svg');
   const num_g_children = svg.node().children.length;
   const g = svg.append('g')
                .attr('transform', `translate(0,${num_g_children*95})`);
       
       g.append('rect')
        .attr('id','node_block')
        .attr('x',50)
        .attr('y',20)
        .attr('rx',20)
        .attr('ry',20)
        .attr('width',145)
        .attr('height',95)
        .attr('transform','translate(0,-15)')
        .attr('fill','white')
        .style('stroke','black')
        .style('stroke-width',5);

       g.append('text')
        .text(clicked_id)
        .attr('id','node_name')
        .attr('x',0)
        .attr('y',15)
        .attr('transform','translate(105,43)');
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<div>
<button onclick=myFunction(~~(10*Math.random()))>Test</button>
<svg class="myViewbox" id="viewBoxId" viewBox="0 0 400 400"  xmlns="http://www.w3.org/2000/svg">
</svg>
</div>


Related Query

More Query from same tag