0

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.

7
  • Calculate the line height and then divide the total content height by that? Commented Jan 13, 2020 at 12:33
  • 3
    What is the business requirement? Sounds like an odd request. Maybe there is a better way to solve the underlying issue. Commented Jan 13, 2020 at 12:34
  • @evolutionxbox I tried that but lineHeight gives me empty "" Commented Jan 13, 2020 at 12:34
  • 2
    You should add this failed attempt to your question Commented Jan 13, 2020 at 12:35
  • 1
    Please show how you used the line height? Commented Jan 13, 2020 at 12:35

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

looks good. But what if the user changes the browser width/height. How can I know that and recalculate?
@user12361681 You have to use it in resize event of window.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.