Sometimes, we want to get the SVG’s text element’s width and height with JavaScript.
In this article, we’ll look at how to get the SVG’s text element’s width and height with JavaScript.
Get the SVG’s Text Element’s Width and Height with JavaScript
To get the SVG’s text element’s width and height with JavaScript, we can call the getBBox
method of the text
element to get the text’s width and height.
For instance, if we have the following SVG:
<svg>
<text x="0" y="20">Some Text</text>
</svg>
Then we can get the text’s width and height by writing
const textElement = document.querySelector('text')
const bbox = textElement.getBBox();
const {
width,
height
} = bbox;
console.log(width, height)
We get the text
element with document.querySelector
.
Then we call getBBox
on the returned textElement
to get an object with the dimensions of the text.
We then destructure the width
and height
to get the text’s width and height respectively.
Conclusion
To get the SVG’s text element’s width and height with JavaScript, we can call the getBBox
method of the text
element to get the text’s width and height.