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

André Pena picture André Pena · Feb 24, 2014 · Viewed 106.1k times · Source

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.

Answer

Christopher Hackett picture Christopher Hackett · Feb 24, 2014

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()