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.