How does one get the height/width of an SVG group element?
Asked Answered
svg
M

3

24

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?

Mustee answered 1/10, 2011 at 13:25 Comment(0)
M
46

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

Mailand answered 3/2, 2012 at 15:38 Comment(3)
Perfect answer - might have used the jQuery version instead since OP is using that: $('g#myGroup').get(0).getBBox().heightFranglais
@ReedSpool that's not the jQuery version. .get just returns the DOM element, jquery does not know about bbox.Retardant
@WillemD'Haeseleer I was pointing out that $().get() could be used instead of the longer document.getElementById(), as the original question uses jQuery. Robert correctly incorporated my suggestion.Franglais
D
4

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.

Drum answered 19/6, 2017 at 12:9 Comment(1)
I tried with both getBBox() and getBoundingClientRect(). Both were showing fn is undefined. And the above answer working fine for me. TxAntitype
C
2

Based on the above answer, you can create jQuery functions .widthSVG() and .heightSVG()

/*
 * .widthSVG(className)
 * Get the current computed width for the first element in the set of matched SVG elements.
 */

$.fn.widthSVG = function(){
    return ($(this).get(0)) ? $(this).get(0).getBBox().width : null;
};

/*
 * .heightSVG(className)
 * Get the current computed height for the first element in the set of matched SVG elements.
 */
$.fn.heightSVG = function(){
    return ($(this).get(0)) ? $(this).get(0).getBBox().height : null;
};
Carpology answered 6/8, 2015 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.