score:1

Computing width and height for <g> elements is exactly the same way i.e. using getBBox(). As the referred link doesn't provide an example, here's one console logging the heights of the <g> elements containing random elements.

var data = [{type: 'text',value: "Test1"}, {type: 'rect', value: {w: 40, h: 70}}, {type: 'circle', value: {r: 12, x: 120}}];

const boxGroup = d3.select('svg').selectAll('.boxes-user')
  .data(data)
  .enter()
  .append("g").classed('boxes-user', true)
  .attr("transform", function (d, i) {
    return "translate(" + (i * 100) + ", 30)";
  }).each(function (d) {
		if(d.type === 'circle') {
    	d3.select(this).append('circle').style('fill', d.value.color || 'steelblue')
         .attr('r', d.value.r || 10).attr('cx', d.value.x || 20);
    } else if(d.type === 'rect') {
  		d3.select(this).append('rect').attr('width', d.value.w || 40).attr('height', d.value.h || 20);  	
    } else {
	    d3.select(this).append('text').text(d.value);
    }    
    // "this" is the group element here. Computing height for the same
    console.log('height of ' + d.type + ': ' + d3.select(this).node().getBBox().height);
  });
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>

<svg width="700" height="500"></svg>

Make sure the elements within it are added before you compute the dimensions or else it'd end up resulting into 0. Hope this clears it up.


Related Query