How to get the width of an svg:g element

I am currently working with an svg element in JavaScript. And I am new to this.

My question is that I have an svg element in which I have multiple svg:g elements. And in my svg:g elements I have various other svg elements.

    <svg>
     <g class="my-class">
      <g class "c1">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
      <g class="c2">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
      <g class="c3">
         <text style="font-size: 9" x="0" y="-4"> john </text>
         <text style="font-size: 9" x="70" y="-4"> 13 </text>
      </g> 
    </g>
   </svg>

g are dynamically appending in my

g "my_class"

Now I want to set my svg width equal to the width of g.my_class width.

var svgWidth  =   $('.my-class').width()
alert(svgWidth);

But its giving me zero. How ever I can see it on my browser in a yellow tool tip boxenter image description here

when I select this line.

Can anyone kindly guide me? Am I doing this right, or how can I achieve this? Thanks


Solution 1:

Try .getBoundingClientRect

$('.my-class')[0].getBoundingClientRect().width;

Demo http://jsfiddle.net/5DA45/

Solution 2:

I'd recommend getBBox (which is part of SVG 1.1) over getBoundingClientRect (which isn't):

$('.my-class')[0].getBBox().width;

Demo http://jsfiddle.net/TAck4/