1
How can I count the number of lines in a div who does not own a \n
or a <br>
at the end of each line? Exemplifying:
var el = document.getElementById('theDiv');
lines = el.innerHTML.replace(/ |^\s+|\s+$/g,'').split('\n'),
lineCount = lines.length;
alert(lineCount); // 5 = correto.
div {
background: #333;
color: #fff;
max-width: 60px;
text-align: center;
}
<div id='theDiv'>
AAAAA
BBBBB
CCCCC
DDDDD
EEEEE
</div>
At the end of each line there is one \n
, then it is simple to do this count only using a split()
. But the problem is: And when there is no such "limit" between one line and another?
Consider the case that "break" is made by a rule in the CSS that sets a maximum width for the div, for example:
var el = document.getElementById('theDiv');
lines = el.innerHTML.replace(/ |^\s+|\s+$/g,'').split('\n'),
lineCount = lines.length;
alert(lineCount); // vai mostrar 1...
div {
background: #333;
color: #fff;
max-width: 60px; /* O css limita a largura e 'quebra' a linha */
text-align: center;
}
<div id='theDiv'>AAAAA BBBBB CCCCC DDDDD EEEEE</div>
The alert()
displayed is not wrong, there really is a single line. But, visually speaking, there are 5 lines like in the previous example.
How can I do this line count?
At first I’m looking for an answer without the use of frameworks, but a response using jQuery will certainly help and be very welcome.
I’m trying to understand, sometimes I get lost in the functions of jQuery.
– Renan Gomes
@Renan the first part puts a span around each letter or space. The second part runs through each span/letter and will see the position span/letter has and compares to see if it has changed line.
– Sergio