Categories
JavaScript Answers

How to Count the Number of Lines of Text Inside a DOM Element with JavaScript?

Spread the love

To get the number of lines in an element, we can divide the element’s height by its line-height.

For instance, if we have the following HTML:

<div style="line-height: 20px">  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tristique nec magna non faucibus. Cras ut mi dignissim, tristique elit at, porta lorem. Pellentesque et odio sed enim commodo commodo in sit amet nunc. Phasellus eu tempus felis, id aliquet leo. Curabitur mollis mauris non dui ornare,  
</div>

Then we can do the computation by writing:

const el = document.querySelector('div');  
const divHeight = +el.offsetHeight  
const lineHeight = +el.style.lineHeight.replace('px', '');  
const lines = divHeight / lineHeight;  
console.log(lines);

We have to set the line height explicitly with the CSS line-height property as we did in the HTML.

Then we select the div with document.querySelector .

Next, we get the div’s height by using the offsetHeight property.

Then we get the lineHeight with the el.style.lineHeight property, we remove the 'px' so that we can convert the string to a number with + .

Next, we divide divHeight by lineHeight to get the number of lines in the div.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *