How can I count text lines inside an DOM element? Can I? Ask Question

How can I count text lines inside an DOM element? Can I? Ask Question

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?

ベストアンサー1

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>

おすすめ記事