Get the number of lines on a textarea

Let's assume that you want to know the number of lines on a <textarea> element.

The trick is to create a dummy element behind <textarea>, and to set it as invisible:

html
<div class = 'container'>
  <textarea 
      id = 'textarea' 
      onkeyup = 'getLines()'>
  </textarea>
  <span id = 'dummy'></span> 
 </div>

Mirror the dummy element and the textarea:

css
.container{
  width: 200px;
}
#dummy, #textarea{
  border: 1px solid gray;
  font-family: sans-serif;
  font-size: small;
  height: 200px;
  left: 0;
  margin: 0;
  padding: 0;
  white-space: pre-wrap;
  top: 0;
  width: 100%
}
#dummy{
  opacity: 0;
}

To get the number of lines, copy the text from the textarea into the dummy element and call getClientRects():

javascript
const getLines = () => {
  
    // Getting both elements, textarea and dummy span
    let textarea = document.getElementById('textarea'); 
    let dummy    = document.getElementById('dummy');
    
    // Copying textarea content into dummy element
    dummy.innerHTML = textarea.value;
    
    // This function returns rectangles tree inside span
    let rectangles = dummy.getClientRects();
    
    // Now you can calculate the number of lines
    let lines = rectangles.length;
  
    return lines;
    
}

You can see a live example on CodePen.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.