How can I count text lines inside an DOM element? Can I?
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;
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:
console.log( message_container.getClientRects().length )
<div style="display:inline;" id="message_container">
..Text of the post..<br>
nice ha?
</div>
Though I don't recommend hard coding the style like that. It's just for example purposes.