In most browsers, the following would work.
window.onload = function(){
console.log( document.getElementById('svgElm').getBoundingClientRect().width );
};
Here is a demo. If you try it in Google Chrome, the console will output 200
. However, FireFox returns 0
.
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.
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.
Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.
The thing is: SVG images don't have a "size" in the sense you are probably thinking of. On the other hand, they DO have a height-to-width ratio. This ratio can usually be found in the viewBox attribute.
I've ended up falling back to the parent dimensions if SVG properties cannot be returned. Here is a demo http://jsbin.com/uzoyik/1/edit.
The relavent code is:
svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight
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