I'm wondering if there's a way to count lines inside a div for example. Say we have a div like so:
<div id="content">hello how are you?</div>
Depending on many factors, the div can have one, or two, or even four lines of text. Is there any way for the script to know?
In other words, are automatic breaks represented in DOM at all?
getClientRects
return the client rects like this and if you want to get the lines, use the follow function like thisIn certain cases, like a link spanning over multiple rows in non justified text, you can get the row count and every coordinate of each line, when you use this:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects
This works because each line would be different even so slightly. As long as they are, they are drawn as a different "rectangle" by the renderer.
For those who use jQuery http://jsfiddle.net/EppA2/3/
Following @BobBrunius 2010 suggestion I created this with jQuery. No doubt it could be improved but it may help some.
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:
And divide by the font line height:
Or to get the line height if it hasn't been explicitly set:
You will also need to take padding and inter-line spacing into account.
EDIT
Fully self-contained test, explicitly setting line-height:
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:
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:
Result:
6 Lines
Works in all browser without rare functions out of standards.
Check: https://jsfiddle.net/gzceamtr/