D3.js: How to get the computed width and height for an arbitrary element?

d3.js, javascript

Solution

For SVG elements

Using something like `selection.node().getBBox()` you get values like

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

For HTML elements

Use `selection.node().getBoundingClientRect()`

Problem

I need to know exactly the width and height for an arbitrary `g` element in my `SVG` because I need to draw a selection marker around it once the user has clicked it. What I've seen in the internet is something like: `d3.select("myG").style("width")`. The problem is that the element will not always have an explicit width attribute set. For instance, when I create a circle inside the `g`, it will have the radious (`r`) set instead of the width. Even if I use the `window.getComputedStyle` method on a `circle`, it will return "auto". Is there a way to calculate the width of an arbitrary `svg` selement in `D3`? Thank you.

Original source