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

Spread the love

Sometimes, we want to count text lines inside a DOM element with JavaScript.

In this article, we’ll look at how to count text lines inside a DOM element with JavaScript.

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

To count text lines inside a DOM element with JavaScript, we divide the element’s height by the 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;

tro get the el element with getElementById.

We get el‘s height with offsetHeight.

And we get its line height with lineHeight.

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

Conclusion

To count text lines inside a DOM element with JavaScript, we divide the element’s height by the line height.

Leave a Reply

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