I need to know the width and height of a SVG element? Im trying to use the following:
$('g#myGroup').height()
...but the result is always zero?
To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el.
To get text element width of an SVG with JavaScript, we can use the getBBox method. const bbox = textElement. getBBox(); const width = bbox. width; const height = bbox.
<g> The <g> SVG element is a container used to group other SVG elements. Transformations applied to the <g> element are performed on its child elements, and its attributes are inherited by its children. It can also group multiple elements to be referenced later with the <use> element.
The <g> element is used to group SVG shapes together. Once grouped you can transform the whole group of shapes as if it was a single shape. This is an advantage compared to a nested <svg> element which cannot be the target of transformation by itself.
svg <g>
elements don't have explicit height and width attributes, they auto size to whatever they contain. You can get their actual height/width by calling getBBox on the element though:
var height = document.getElementById("myGroup").getBBox().height;
If you're really into jquery you could write it as
$('g#myGroup').get(0).getBBox().height;
according to Reed Spool
I wasn't able to get any of the answers above to work, but did come across this solution for finding it with d3:
var height = d3.select('#myGroup').select('svg').node().getBBox().height; var width = d3.select('#myGroup').select('svg').node().getBBox().width;
getBBox() here will find the actual width and height of the group element. Easy as that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With