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 box
when I select this line.
Can anyone kindly guide me? Am I doing this right, or how can I achieve this? Thanks
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.
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.
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.
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.
Try .getBoundingClientRect
$('.my-class')[0].getBoundingClientRect().width;
Demo http://jsfiddle.net/5DA45/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With