Thursday, October 23, 2025
HomeLanguagesJavascriptHow to count text lines inside of DOM element ?

How to count text lines inside of DOM element ?

In this article, we will see how to count the number of text lines inside of the DOM element. To count the number of text lines inside the DOM element, we will use the following approach.

  • Obtain the total height of the content inside the DOM element.
  • Obtain the height of one line.
  • By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.

Example: This example uses the above approach and prints the number of text lines inside the DOM element.

html




<h1 style="color: green;">
    GeeksForGeeks
</h1>
  
<div id="content" style="width: 100%; 
                line-height: 20px">
    hello how are you?<br>
    hello how are you?<br>
    hello how are you? <br>
    hello how are you?<br>
</div>
  
<button onclick="countLines()">
    Count lines
</button>
  
<script>
    // Function to count total
    // number of lines
    function countLines() {
      
        // Get element with 'content' as id                            
        var el = 
            document.getElementById('content');
      
        // Get total height of the content    
        var divHeight = el.offsetHeight
      
        // object.style.lineHeight, returns 
        // the lineHeight property
        // height of one line 
        var lineHeight = 
            parseInt(el.style.lineHeight);
      
        var lines = divHeight / lineHeight;
        alert("Lines: " + lines);
    }
</script>


Output:

How to count text lines inside of DOM element ?

How to count text lines inside of DOM element ?

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS