How to get the width of an svg:g element

A_user picture A_user · Jul 28, 2012 · Viewed 45.7k times · Source

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

Answer

Esailija picture Esailija · Jul 28, 2012

Try .getBoundingClientRect

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

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