How to get the width of an svg:g element

JavascriptJquerySvgWidth

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Try .getBoundingClientRect

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

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

Solution 2 - Javascript

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionA_userView Question on Stackoverflow
Solution 1 - JavascriptEsailijaView Answer on Stackoverflow
Solution 2 - JavascriptErik DahlströmView Answer on Stackoverflow