Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one get the height/width of an SVG group element?

Tags:

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?

like image 879
josef.van.niekerk Avatar asked Oct 01 '11 13:10

josef.van.niekerk


People also ask

How do I get SVG width and height?

To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el.

How do you find the width of an SVG text element?

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.

What is SVG Group Element?

<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.

What is the use of G tag?

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.


2 Answers

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

like image 168
Robert Longson Avatar answered Nov 04 '22 15:11

Robert Longson


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.

like image 36
Kyle Krzeski Avatar answered Nov 04 '22 15:11

Kyle Krzeski