JSFiddle - React, Tailwind, and code Playground

by Sinh Nguyen

HTML

<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>
<span id="span-01">eaf5f32b-c32...</span>
<script type="text/javascript">
    function getTextWidth() { 
       const text = document.createElement("span");
          text.style.fontSize = 12 + "px";
          text.style.height = 'auto'; 
          text.style.width = 'auto'; 
          text.style.position = 'absolute'; 
          text.style.whiteSpace = 'no-wrap'; 
          text.innerHTML = 'eaf5f32b-c32...'; 
          document.body.appendChild(text);
          const width = Math.ceil(text.clientWidth); 
          console.log('width: ' + width);
          document.body.removeChild(text); 
    }
    getTextWidth();
</script>