I have a textarea
with the the text Hello World
. I would like to get the height of this text.
I've tried to use:
var element = document.getElementById('textarea'); var textHeight = element.innerHTML.offsetHeight;
and:
var textHeight = element.value.offsetHeight;
But these don't give the numbers of the text, but the height of the textarea
element.
<textarea> does not support the value attribute.
The value property sets or returns the contents of a text area. Note: The value of a text area is the text between the <textarea> and </textarea> tags.
element.scrollHeight is probably worth investigating.
If I was going to approach this (and I've not tested this at all), I'd set the textarea's height to 1px measure the scroll height and then reset the textarea's height.
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
Create a span element, set Span's innerHTML to "Hello World".
Get the span's offsetHeight.
var span = document.createElement("span"); span.innerHTML="Hello World"; //or whatever string you want. span.offsetHeight // this is the answer
note that you must set the span's font style to the textarea's font style.
Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.
If you wish to get the height of selected text inside of a textarea, use selectionStart/selectionEnd to find the selected text of the textarea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With