Divide the Element's Height by its Line Height To get the number of lines in an element, we can divide the element's height by its line-height. Then we can do the computation by writing: const el = document. querySelector('div'); const divHeight = +el.
To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);
To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character. Then we get the length of the returned string array.
If the div's size is dependent on the content (which I assume to be the case from your description) then you can retrieve the div's height using:
var divHeight = document.getElementById('content').offsetHeight;
And divide by the font line height:
document.getElementById('content').style.lineHeight;
Or to get the line height if it hasn't been explicitly set:
var element = document.getElementById('content');
document.defaultView.getComputedStyle(element, null).getPropertyValue("lineHeight");
You will also need to take padding and inter-line spacing into account.
EDIT
Fully self-contained test, explicitly setting line-height:
function countLines() {
var el = document.getElementById('content');
var divHeight = el.offsetHeight
var lineHeight = parseInt(el.style.lineHeight);
var lines = divHeight / lineHeight;
alert("Lines: " + lines);
}
<body onload="countLines();">
<div id="content" style="width: 80px; line-height: 20px">
hello how are you? hello how are you? hello how are you? hello how are you?
</div>
</body>
Check out the function getClientRects() which can be used to count the number of lines in an element. Here is an example of how to use it.
var message_lines = $("#message_container")[0].getClientRects();
It returns a javascript DOM object. The amount of lines can be known by doing this:
var amount_of_lines = message_lines.length;
It can return the height of each line, and more. See the full array of things it can do by adding this to your script, then looking in your console log.
console.log("");
console.log("message_lines");
console.log(".............................................");
console.dir(message_lines);
console.log("");
Though a few things to note is it only works if the containing element is inline, however you can surround the containing inline element with a block element to control the width like so:
<div style="width:300px;" id="block_message_container">
<div style="display:inline;" id="message_container">
..Text of the post..
</div>
</div>
Though I don't recommend hard coding the style like that. It's just for example purposes.
One solution is to enclose every word in a span tag using script. Then if the Y dimension of a given span tag is less than that of it's immediate predecessor then a line break has occurred.
I wasnt satisfied with the answers here and on other questions. The highest rated answer doesn't take padding
or border
into account, and therefore obviously ignores box-sizing
as well. My answer combines some techniques here and and on other threads to get a solution that works to my satisfaction.
It isnt perfect: When no numerical value was able to be retrieved for the line-height
(e.g. normal
or inherit
), it just uses the font-size
multiplied by 1.2
. Perhaps someone else can suggest a reliable way to detect the pixel value in those cases.
Other than that, it has been able to correctly handle most of the styles and cases I have thrown at it.
jsFiddle for playing around and testing. Also inline below.
function countLines(target) {
var style = window.getComputedStyle(target, null);
var height = parseInt(style.getPropertyValue("height"));
var font_size = parseInt(style.getPropertyValue("font-size"));
var line_height = parseInt(style.getPropertyValue("line-height"));
var box_sizing = style.getPropertyValue("box-sizing");
if(isNaN(line_height)) line_height = font_size * 1.2;
if(box_sizing=='border-box')
{
var padding_top = parseInt(style.getPropertyValue("padding-top"));
var padding_bottom = parseInt(style.getPropertyValue("padding-bottom"));
var border_top = parseInt(style.getPropertyValue("border-top-width"));
var border_bottom = parseInt(style.getPropertyValue("border-bottom-width"));
height = height - padding_top - padding_bottom - border_top - border_bottom
}
var lines = Math.ceil(height / line_height);
alert("Lines: " + lines);
return lines;
}
countLines(document.getElementById("foo"));
div
{
padding:100px 0 10% 0;
background: pink;
box-sizing: border-box;
border:30px solid red;
}
<div id="foo">
x<br>
x<br>
x<br>
x<br>
</div>
Clone the container object and write 2 letters and calculate the height. This return the real height with all style applied, line height, etc. Now, calculate the height object / the size of a letter. In Jquery, the height excelude the padding, margin and border, it is great to calculate the real height of each line:
other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
lines = obj.height() / size;
If you use a rare font with different height of each letter, this does not works. But works with all normal fonts, like Arial, mono, comics, Verdana, etc. Test with your font.
Example:
<div id="content" style="width: 100px">hello how are you? hello how are you? hello how are you?</div>
<script type="text/javascript">
$(document).ready(function(){
calculate = function(obj){
other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
return obj.height() / size;
}
n = calculate($('#content'));
alert(n + ' lines');
});
</script>
Result: 6 Lines
Works in all browser without rare functions out of standards.
Check: https://jsfiddle.net/gzceamtr/
For those who use jQuery http://jsfiddle.net/EppA2/3/
function getRows(selector) {
var height = $(selector).height();
var line_height = $(selector).css('line-height');
line_height = parseFloat(line_height)
var rows = height / line_height;
return Math.round(rows);
}
I am convinced that it is impossible now. It was, though.
IE7’s implementation of getClientRects did exactly what I want. Open this page in IE8, try refreshing it varying window width, and see how number of lines in the first element changes accordingly. Here’s the key lines of the javascript from that page:
var rects = elementList[i].getClientRects();
var p = document.createElement('p');
p.appendChild(document.createTextNode('\'' + elementList[i].tagName + '\' element has ' + rects.length + ' line(s).'));
Unfortunately for me, Firefox always returns one client rectangle per element, and IE8 does the same now. (Martin Honnen’s page works today because IE renders it in IE compat view; press F12 in IE8 to play with different modes.)
This is sad. It looks like once again Firefox’s literal but worthless implementation of the spec won over Microsoft’s useful one. Or do I miss a situation where new getClientRects may help a developer?
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