Categories
JavaScript Answers

How to Get the SVG’s Text Element’s Width and Height with JavaScript?

Spread the love

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.

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 *