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

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


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


.getBoundingClientRect() returns the size of an element and its position relative to the viewport.We can easily get following

  • left, right
  • top, bottom
  • height, width

Example :

var element = d3.select('.elementClassName').node();element.getBoundingClientRect().width;


Once I faced with the issue when I did not know which the element currently stored in my variable (svg or html) but I needed to get it width and height. I created this function and want to share it:

function computeDimensions(selection) {  var dimensions = null;  var node = selection.node();  if (node instanceof SVGGraphicsElement) { // check if node is svg element    dimensions = node.getBBox();  } else { // else is html element    dimensions = node.getBoundingClientRect();  }  console.log(dimensions);  return dimensions;}

Little demo in the hidden snippet below. We handle click on the blue div and on the red svg circle with the same function.