How to get the height of the text inside of a textarea

Viewed 48924

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.

8 Answers

You can get the text height by getting the textarea scrollbar height

const textarea = document.getElementByTagName("textarea");
const height = textarea.scrollHeight;

console.log({ height });

For anyone using React:

const textarea_ref = useRef(null);
const [idealHeight,setIdealHeight] = useState(0);
const [inputValue,setInputValue] = useState("");


useLayoutEffect(() => {                                           // useLayoutEffect TO AVOID FLICKERING
    textarea_ref.current.style.height = '0px';                    // NEEDS TO SET HEIGHT TO ZERO
    const scrollHeight = textarea_ref.current.scrollHeight;       // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
    textarea_ref.current.removeAttribute('style');                // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
    setIdealHeight(scrollHeight + 2);                             // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
  },[inputValue]);

return (
  <textarea
    // USE idealHeight STATE TO SET THE HEIGHT
    value={inputValue}
    onChange={onChange}
    ref={textarea_ref}
  />
);

PS: It still flickers sometimes. At least in Chrome.

Related