skip to Main Content

I want to display the length of a span tag on my web page. I researched for ways but could not find one.

I researched for ways but could not find one. Is there a way if not please tell me. I am using vuejs2 so if there is a way with vuejs2, then please tell me so.

<span>Hello World!</span>
<p>
  <!-- The width of span tag above goes here with document.getElementById("").innerHTML -->
</p>

3

Answers


  1. YOu get the width in pixel by using offsetWidth and the width in chars by using textContent.length.

    If you want to print it into another element, you need to reference the element and can include it with textContent as well. Outputting some JS calculations is not suitable for a <p> as it expects flow-text but for an <output> element!

    const SPAN = document.querySelector('span');
    
    // get width in pixel
    console.log(`width in pixel: ${SPAN.offsetWidth}px`);
    
    // width in chars
    console.log(`width in chars: ${SPAN.textContent.length}`);
    <span>Hello World</span>

    PS: You should not use innerHTML to write an output as it is comparable slow (reparsing DOM) and poses security issues (XSS injections). If you just want to print an output use textContent.

    Login or Signup to reply.
  2. I assume you mean the width in pixels?

    If so, you’d do something like this:

    // give your span a class 
    // <span class='test-span'>test</span>
    
    // create a function to get the width
    function getSpanWidth() {
      let span = document.querySelector('.test-span')
      let width = span.offsetWidth
      
      return width
     }

    Offset width includes the padding.

    Login or Signup to reply.
  3. To find the length in text characters, you can simply use the textContent.length property for strings.

    Code:

    <!DOCTYPE html>
    <html>
    <span id="test1">Hello World!</span>
    <p id="test2">
      <!-- The width of span tag above goes here with document.getElementById("").innerText -->
    </p>
    <script>
      var spanLength = document.getElementById("test1").textContent.length;
      document.getElementById("test2").innerText = spanLength;
    </script>
    
    </html>

    Also the innerHTML property isn’t for changing text in an element, it is for adding new html elements inside that element. Use innerText instead.

    Now, if you want the width of an html element in px, you can use the offsetWidth property.

    Code:

    <!DOCTYPE html>
    <html>
    <span id="test1">Hello World!</span>
    <p id="test2">
      <!-- The width of span tag above goes here with document.getElementById("").innerText -->
    </p>
    <script>
      var spanLength = document.getElementById("test1").offsetWidth;
      document.getElementById("test2").innerText = spanLength + "px";
    </script>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search