Categories
JavaScript Answers

How to get width and height of SVG element with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *