How to count text lines inside of DOM element ?

To count number of text lines inside DOM element, we will use the following approach.

  1. Obtain the total height of content inside the DOM element.
  2. Obtain the height of one line.
  3. 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:

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>Count lines </title>
</head>
  
<body>
    <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>
</body>
  
</html>

chevron_right


  • Before Clicking on the button:
     
  • After Clicking on the button:
     

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.