josef.van.niekerk
josef.van.niekerk

Reputation: 12121

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

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?

Upvotes: 24

Views: 26668

Answers (3)

Kyle Krzeski
Kyle Krzeski

Reputation: 6527

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.

Upvotes: 4

Sagar Gala
Sagar Gala

Reputation: 944

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;
};

Upvotes: 2

Robert Longson
Robert Longson

Reputation: 124059

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

Upvotes: 47

Related Questions