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.
var svg = d3.select('svg')
.attr('width', 50)
.attr('height', 50);
function computeDimensions(selection) {
var dimensions = null;
var node = selection.node();
if (node instanceof SVGElement) {
dimensions = node.getBBox();
} else {
dimensions = node.getBoundingClientRect();
}
console.clear();
console.log(dimensions);
return dimensions;
}
var circle = svg
.append("circle")
.attr("r", 20)
.attr("cx", 30)
.attr("cy", 30)
.attr("fill", "red")
.on("click", function() { computeDimensions(circle); });
var div = d3.selectAll("div").on("click", function() { computeDimensions(div) });
_x000D_
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #ffd;
}
.div {
display: inline-block;
background-color: blue;
margin-right: 30px;
width: 30px;
height: 30px;
}
_x000D_
<h3>
Click on blue div block or svg circle
</h3>
<svg></svg>
<div class="div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_