Calculate the width of the text in JavaScript - GeeksforGeeks

31 Jul, 2019
Method 1: Creating a new DOM Element and measuring its width: A new “span” element is created with the createElement() method. Then added it to the body of the element using the appendChild() method. The style property of this element is used to set properties like the font, font-size, height, width, whiteSpace, and position.The font is set to the string with the font needed. The font-size is a string with a value in pixels. The height and width properties are set to ‘auto’. The position property is set to ‘absolute’ and the whiteSpace property is set to ‘no-wrap’. The text to be measured is specified using the innerHTML property. The clientWidth property is used to get the width of its element. This value will represent the width of text in pixels. The element is then removed using the removeChild() method.
Example:
<!DOCTYPE html><html>      <head>    <title>        Calculate the text width        with JavaScript     </title></head>  <body>    <h1 style="color: green">        GeeksforGeeks    </h1>          <b>        Calculate text width         with JavaScript    </b>           <p>        Text to calculate width is        "Hello World"    </p>    <p>Font size of the text is 16px</p>          <p>        Width of the text is:        <span class="output"></span>    </p>          <button onclick="getTextWidth()">        Calculate text width    </button>          <script type="text/javascript">        function getTextWidth() {              text = document.createElement("span");            document.body.appendChild(text);              text.style.font = "times new roman";            text.style.fontSize = 16 + "px";            text.style.height = 'auto';            text.style.width = 'auto';            text.style.position = 'absolute';            text.style.whiteSpace = 'no-wrap';            text.innerHTML = 'Hello World';              width = Math.ceil(text.clientWidth);            formattedWidth = width + "px";              document.querySelector('.output').textContent                    = formattedWidth;            document.body.removeChild(text);        }    </script></body>  </html>    
Output:
Before clicking the button:
After clicking the button:
Method 2: Using the canvas measureText() method: A new “canvas” element is created with the createElement() method. The 2d context required to draw graphics is accessed using the getContext() method and passing the value “2d” as the parameter. This context will be used to manipulate the text in the canvas. The font is specified using the font property. The font string uses the same syntax as a CSS font specifier.The dimensions of the text are calculated using the measureText() method. The text to be measured is passed to this method. It returns a TextMetrics object that contains information about the measured text. The width property of this TextMetrics object is used to get the width of the text. The width may be a floating-point value, hence the Math.ceil() function is used to find the ceiling of the floating-point and return an integer. This value is the width of the measured text in pixels.
Example:
<!DOCTYPE html><html>  <head>    <title>        Calculate the text width with JavaScript    </title></head>  <body>    <h1 style="color: green">        GeeksforGeeks    </h1>          <b>Calculate text width with JavaScript</b>           <p>        Text to calculate width is         "Geeks For Geeks"    </p>          <p>Font size of the text is 16px</p>          <p>        Width of the text is:         <span class="output"></span>    </p>          <button onclick="getTextWidth()">        Calculate text width    </button>          <script type="text/javascript">        function getTextWidth() {              inputText = "Geeks For Geeks";            font = "16px times new roman";              canvas = document.createElement("canvas");            context = canvas.getContext("2d");            context.font = font;            width = context.measureText(inputText).width;            formattedWidth = Math.ceil(width) + "px";              document.querySelector('.output').textContent                        = formattedWidth;        }    </script></body>  </html>    
Output:
Before clicking the button:
After clicking the button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?