I have a <textarea>
element. Can I use JavaScript to detect that there are (for example) 10 rows of text in it?
-
1You might want to clarify your question so it doesn't look like you are trying to return the `rows=` attribute from the `textarea` element. – Doug Neiner Nov 19 '09 at 03:09
-
3Why would you want to do this? I sense a bad requirement specification. – Randell Nov 19 '09 at 03:23
7 Answers
Well I found a much simplier way to do this, but you'll need to set the line-height of the textarea in the CSS. I tried to read the line height inside the script ta.style.lineHeight
but it doesn't seem to return a value.
CSS
#ta { width: 300px; line-height: 20px; }
HTML
<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>
Script
var taLineHeight = 20; // This should match the line-height in the CSS
var taHeight = ta.scrollHeight; // Get the scroll height of the textarea
ta.style.height = taHeight; // This line is optional, I included it so you can more easily count the lines in an expanded textarea
var numberOfLines = Math.floor(taHeight/taLineHeight);
alert( "there are " + numberOfLines + " lines in the text area");
Update: Thanks to @Pebbl for working out the bugs, this is the code needed to get the height of the text content (demo)
var calculateContentHeight = function( ta, scanAmount ) {
var origHeight = ta.style.height,
height = ta.offsetHeight,
scrollHeight = ta.scrollHeight,
overflow = ta.style.overflow;
/// only bother if the ta is bigger than content
if ( height >= scrollHeight ) {
/// check that our browser supports changing dimension
/// calculations mid-way through a function call...
ta.style.height = (height + scanAmount) + 'px';
/// because the scrollbar can cause calculation problems
ta.style.overflow = 'hidden';
/// by checking that scrollHeight has updated
if ( scrollHeight < ta.scrollHeight ) {
/// now try and scan the ta's height downwards
/// until scrollHeight becomes larger than height
while (ta.offsetHeight >= ta.scrollHeight) {
ta.style.height = (height -= scanAmount)+'px';
}
/// be more specific to get the exact height
while (ta.offsetHeight < ta.scrollHeight) {
ta.style.height = (height++)+'px';
}
/// reset the ta back to it's original height
ta.style.height = origHeight;
/// put the overflow back
ta.style.overflow = overflow;
return height;
}
} else {
return scrollHeight;
}
}
var calculateHeight = function() {
var ta = document.getElementById("ta"),
style = (window.getComputedStyle) ?
window.getComputedStyle(ta) : ta.currentStyle,
// This will get the line-height only if it is set in the css,
// otherwise it's "normal"
taLineHeight = parseInt(style.lineHeight, 10),
// Get the scroll height of the textarea
taHeight = calculateContentHeight(ta, taLineHeight),
// calculate the number of lines
numberOfLines = Math.ceil(taHeight / taLineHeight);
document.getElementById("lines").innerHTML = "there are " +
numberOfLines + " lines in the text area";
};
calculateHeight();
if (ta.addEventListener) {
ta.addEventListener("mouseup", calculateHeight, false);
ta.addEventListener("keyup", calculateHeight, false);
} else if (ta.attachEvent) { // IE
ta.attachEvent("onmouseup", calculateHeight);
ta.attachEvent("onkeyup", calculateHeight);
}

- 84,355
- 30
- 126
- 241
-
2+1, this is by far the most reliable approach. One note: Ensure that the textarea starts with `rows=1`, or else its `scrollHeight` may be artificially high. – Trevor Burnham Jun 13 '12 at 17:50
-
1@Mottie the `.style` object will only ever return inline styles. To get the computed value you should use `window.getComputedStyle` and fallback to `Elm.currentStyle` for old IE. Other than that +1 :) – Pebbl Nov 23 '12 at 10:22
-
1Thanks for the input @pebbl! I've combined the above suggestions and made [a demo](http://jsfiddle.net/Mottie/PfD7L/). Note that when you manually resize the textarea in modern browsers, the number of lines will change to match the resized height and not the content. – Mottie Nov 23 '12 at 15:06
-
4@Mottie nice one :) if you're interested I've combined some auto-resize textarea logic with your line count and so now it should be fullproof -- for most browsers -- even if the ta is larger than the content. http://jsfiddle.net/PfD7L/1/ – Pebbl Nov 24 '12 at 11:31
-
@Pebbl I know it's been a few years, but I found a minor problem in the demo, the `numberOfLines` calculation should be using `Math.ceil()` instead of floor. I updated my answer; thanks again for your assistance :) – Mottie Mar 17 '15 at 12:34
-
Is there a potential for an infinite loop on ```while (ta.offsetHeight >= ta.scrollHeight) { ta.style.height = (height -= scanAmount)+'px'; }```? ta.offsetHeight is unchanged by the loop, so the loop continues forever, no? – VikR Feb 09 '18 at 02:02
-
-
3i have lineHeight=20 and textarea height=40, while i adding text, calculateContentHeight returning 21, 41, 60, 80, 100. `(height++)+'px'` need to be replaced by `(++height)+'px'` – Matveev Dmitriy Feb 15 '18 at 14:56
-
@VikR, actually we hit infinite loop here with crome and 75% scale. Chrome DOM reported strange sizes here, so we decided to use similar approach as http://www.jacklmoore.com/autosize/ uses without loops – Dec 27 '18 at 15:25
-
Hello @Mottie. Thanks for this answer works just fine. Can you or someone else explain little bit more why we need this line :ta.style.height = (height + scanAmount) + 'px'; and why do we need the two while statements. – ilce Aug 16 '21 at 21:27
-
All `textarea`s have a default height, or a height set using the [`rows` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-rows). If the content height is less than this value, the resulting count is inaccurate. The first `while` loop reduces the height by `scanAmount` (line height) until it is it greater than or equal to the content height. The second `while` loop expands the height 1 pixel at a time until it matches. If you only need a rough estimate, use the code in the first snippet (5 lines of code). – Mottie Aug 17 '21 at 21:58
-
@Mottie Sorry, I don't understand why the scans are there at all. Once you set the textarea height to zero like `ta.style.height = 0` you may read the `ta.scrollHeight` right away to get the precise content height in pixels. So the code will look like: `var origHeight = ta.style.height; ta.style.heihgt = '0'; height = ta.scrollHeight; ta.style.height = origHeight;` Do I miss somtthing? – Sergey Dec 07 '21 at 09:43
-
Thanks for the solution :) However, in the code above, there's "textarea.scrollHeight" which requires the and it's parent element visible in the page, this should be the prerequisite condition one might get stuck like me. Reference: https://stackoverflow.com/questions/14231481/read-scrollheight-of-div-with-a-displaynone-parent – mike652638 Jun 22 '22 at 08:25
You can get the actual text height from Element.scrollHeight
, but to get the correct height, there has to be a scroll, which means you can temporarily set the text box height to 0
, until you get the scroll height value then restore back the CSS height.
One you have that, you calculate the number of lines based on the CSS line-height property value (1 line of text contributes to getComputedStyle(ref).lineHeight
pixels), something like...
function getTextareaNumberOfLines(textarea) {
var previous_height = textarea.style.height, lines
textarea.style.height = 0
lines = parseInt( textarea.scrollHeight/parseInt(getComputedStyle(textarea).lineHeight) )
textarea.style.height = previous_height
return lines
}
Note: your elements must be present in the DOM in order to get the scrollHeight, lineHeight heights etc. If not already present, add them, calculate the values, then remove them from the DOM.

- 725
- 8
- 23
-
Make sure `line-height` css property is a numeric value (i.e not `normal` or similar strings) – Ismail Oct 30 '21 at 17:22
Assuming you know the line-height, the simplest way to do this would be:
function numOfLines(textArea, lineHeight) {
var h0 = textArea.style.height;
ta.style.height = 'auto';
var h1 = textArea.scrollHeight;
textArea.style.height = h0;
return Math.ceil(h1 / lineHeight);
}
The trick here is to set the height to auto
first. Then when you access scrollHeight the browser will do the layout and return the correct height including any line wraps. Then restore the textarea height to its original value and return the result.

- 61
- 1
- 1
Just one js line:
var rows = document.querySelector('textarea').value.split("\n").length;

- 1,243
- 1
- 11
- 9
-
1I've run into problems with this one, depending on the OS. In particular the difference between \r, \r\n, \n\r, and \n. I don't remember exactly why, but it was actually quite difficult to exhaustively do it this way. – mike Sep 14 '15 at 20:28
-
37What if there are several lines not because of newline characters but because one line overflows to the next line? – intcreator Jun 14 '17 at 06:47
-
You can access the field via Javascript DOM and simply count the number of newline characters.
oArea = document.getElementById('myTextField');
var aNewlines = oArea.value.split("\n");
var iNewlineCount = aNewlines.length();

- 420
- 3
- 10
-
5This will only work for
. If the text auto-wraps the only way to do it is to use a fixed-size font, count all chars and then divide them by the allowed chars in a row. And that assuming there are no newlines in the process... \n anyone?! – Frankie Nov 19 '09 at 03:25 -
You could turn wrapping off if that is an option which would make the number of newlines = number of rows – John Scipione Nov 19 '09 at 03:36
-
@Mask look into thephpdeveloper answer. It's a more elegant approach than mine. – Frankie Nov 19 '09 at 03:37
-
@Frankie ,but I don't understand his approach,how is it supposed to calculate the rows? – Mask Nov 19 '09 at 03:42
function countLines(area,maxlength) {
// var area = document.getElementById("texta")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "")
var split = text.split("\n")
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than "+maxlength.toString()+" lines");
}
return false;
}
this is a simple and tested one
-
3
-
2Sure it does. A break of a line does not definitively signify a newline, however. – dvlsg Nov 14 '14 at 19:10
The simple way:
var lines = document.querySelector("textarea").value.split(/\r\n|\r|\n/).length;

- 129
- 3