How do I count the number of rows within a div that does not have a "line constraint"?

1

How can I count the number of rows in a div that does not have a \n or a <br> at the end of each row? 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 \n , so it's simple to do this count only using a split() . But the problem is: And when there is no such "boundary" between one line and another?

Consider the case of "break" being made by a rule in CSS that defines a maximum width for 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 only one line. But visually speaking, there are 5 lines as 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 will be very welcome.

    

asked by anonymous 20.05.2015 / 16:53

2 answers

1

In addition to the width, set the line-height of the element through css:

div {
    max-width: 60px;
    line-height: 14px;
}

And with javascript just divide the height of the element by the height of the line:

var minhaDiv = document.getElementById("conteudo"),
    estiloComputado = window.getComputedStyle(minhaDiv),
    alturaDiv = minhaDiv.offsetHeight,
    alturaLinha = parseInt(estiloComputado.getPropertyValue("line-height"));

alert(alturaDiv / alturaLinha);

Example working on SQLFiddle .

    
20.05.2015 / 17:58
2

I came up with this idea: put <span> around each character and check if the vertical position is the same as the next one. If it does not then there was a change of line:)

Of course this implies that there is no CSS applied to #theDiv span but this is easy to do a reset.

var text = $('#theDiv').text();
var newText = text.split('').map(function (letra) {
    return ['<span>', letra, '</span>'].join('');
}).join('');
$('#theDiv').html(newText);

var linhas = 1;
var ultimaLinha;
$('#theDiv span').each(function () {
    var pos = this.getBoundingClientRect().bottom;
    if (ultimaLinha && pos != ultimaLinha) linhas++;
    ultimaLinha = pos;
});
alert(linhas); // 5

jsFiddle: link

    
20.05.2015 / 17:05