user12361681
user12361681

Reputation: 107

Count lines in HTML with Javascript

I need a way to count lines in the html so I can do logic for a business requirement.

I use Bootstrap + AngularJS but the solution could be in plain Javascript.

I have no idea where to start. Any help?

.myClass {
  word-break: break-all;
  white-space: pre-line;
}
<div style="max-width: 50px">
  <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
<span>Total Lines: <b id="totalLines"></b></span>

I also would need a way to calculate this everytime the user makes the window smaller/bigger because of the responsive aspect.

Upvotes: 0

Views: 641

Answers (1)

Saurin Vala
Saurin Vala

Reputation: 1928

getClientRects will be useful here

The getClientRects() method of the Element interface returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client.

$("#totalLines").text($(".myClass")[0].getClientRects().length);
console.log($(".myClass")[0].getClientRects().length);

$(document).ready(function() { 
                $(window).resize(function() { 
                console.log("Resize event fired");
                   $("#totalLines").text($(".myClass")[0].getClientRects().length);
                }); 
            }); 
.myClass {
  word-break: break-all;
  white-space: pre-line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="max-width: 500px">
  <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
<span>Total Lines: <b id="totalLines"></b></span>

Upvotes: 1

Related Questions