Sometimes, we want to get width and height of SVG element with JavaScript.
In this article, we’ll look at how to get width and height of SVG element with JavaScript.
How to get width and height of SVG element with JavaScript?
To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method.
For instance, we write
const el = document.getElementById("yourElement");
const rect = el.getBoundingClientRect();
console.log(rect.width);
console.log(rect.height);
to call getElementById to get the element.
Then we call getBoundingClientRect to return an object with the width and height of the element.
Conclusion
To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method.