Sometimes, we want to count text lines inside an DOM element with JavaScript.
In this article, we’ll look at how to count text lines inside an DOM element with JavaScript.
How to count text lines inside an DOM element with JavaScript?
To count text lines inside an DOM element with JavaScript, we can divide the element height by 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;
to select the div with getElementById
.
Then we get the div’s height with offsetHeight
.
And then we get the lineHeight
from the div.
Finally, we get number of lines of text by dividing divHeight
and lineHeight
.
Conclusion
To count text lines inside an DOM element with JavaScript, we can divide the element height by its line height.