Categories
JavaScript Answers

How to count text lines inside an DOM element with JavaScript?

Spread the love

To count text lines inside an DOM element with JavaScript, we can calculate it from the element height and its line height.

For instance, we write

const el = document.getElementById("content");
const divHeight = el.offsetHeight;
const lineHeight = parseInt(el.style.lineHeight);
const lines = divHeight / lineHeight;
console.log(lines);

to get the element with getElementById.

We get its height with offsetHeight.

We get its line height with el.style.lineHeight.

Then we divide divHeight by lineHeight to get the number of lines.

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 *