
Find the number of lines in a div?
1 Expert Answer
Rize S. answered 03/23/23
Master's in MISM, 25 yrs Exp: HTML Expert
One approach could be to create a hidden div with the same content as the target div, set its height to a fixed value (e.g. 1em), and check its scrollHeight property to see how many lines the content takes up. Here's an example code snippet:
var lineHeight = parseInt($('#target-div').css('line-height')); // get line height in pixels
var lineHeightEm = lineHeight / parseFloat($('body').css('font-size')); // convert to em units
var hiddenDiv = $('<div>').css({
position: 'absolute',
top: '-9999px',
left: '-9999px',
visibility: 'hidden',
width: $('#target-div').width(),
'font-size': $('#target-div').css('font-size'),
'line-height': lineHeightEm + 'em'
}).html($('#target-div').html()).appendTo('body');
var numLines = Math.round(hiddenDiv.get(0).scrollHeight / lineHeight);
console.log(numLines); // output the number of lines
In this code, we first get the line height of the target div in pixels, convert it to em units, and create a hidden div with the same font size and line height. We then copy the HTML content of the target div to the hidden div and append it to the body. Finally, we check the hidden div's scrollHeight property and divide it by the line height to get the number of lines.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Shaquon K.
11/02/22