Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 971
A_user Avatar asked Jul 28 '12 16:07

A_user


People also ask

How do you find the width of an SVG text element?

To get text element width of an SVG with JavaScript, we can use the getBBox method. const bbox = textElement. getBBox(); const width = bbox. width; const height = bbox.

How do I get SVG width and height?

To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el. getBoundingClientRect(); console.

What is the G element in SVG?

The SVG <g> element is a container used to group other SVG elements. Transformations applied to the <g> element are also performed on its child elements, and its attributes are inherited by its children.

Does SVG need width and height?

SVG images, in contrast, can be drawn at any pixel size, so they don't need a clearly defined height or width. And they won't always have a clearly defined aspect ratio.


Video Answer


1 Answers

Try .getBoundingClientRect

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

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

like image 78
Esailija Avatar answered Sep 24 '22 17:09

Esailija