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
YOu get the width in pixel by using
offsetWidth
and the width in chars by usingtextContent.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!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 usetextContent
.I assume you mean the width in pixels?
If so, you’d do something like this:
Offset width includes the padding.
To find the length in text characters, you can simply use the textContent.length property for strings.
Code:
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: