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?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
josef.van.niekerk
  • 11,941
  • 20
  • 97
  • 157

3 Answers3

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

Robert Longson
  • 118,664
  • 26
  • 252
  • 242
  • Perfect answer - might have used the jQuery version instead since OP is using that: $('g#myGroup').get(0).getBBox().height – Reed Spool Sep 29 '14 at 16:30
  • @ReedSpool that's not the jQuery version. `.get` just returns the DOM element, jquery does not know about bbox. – Willem D'Haeseleer Dec 27 '15 at 23:37
  • @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. – Reed Spool Dec 28 '15 at 00:16
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.

Kyle Krzeski
  • 6,183
  • 6
  • 41
  • 52
  • 1
    I tried with both getBBox() and getBoundingClientRect(). Both were showing fn is undefined. And the above answer working fine for me. Tx – Nisfan Dec 26 '17 at 13:18
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;
};
Sagar Gala
  • 944
  • 10
  • 10