0

Consider the p element below.

<p>A B C D E F G H I J K L M N O P Q R S T U V W X Y Z qwertyuiopasdfghjklzxcvbnm 122333444455555666666777777788888888999999999</p>

In my current screen-size, in my particular browser, it took 3 whole lines to type this piece of html code inside the checkbox element in which I am typing this question.

Now if this were a p element in a real html page, the number of lines would have depended on multiple factors such as font-size, font-family, letter-spacing, font-weight, number of characters, viewport width, the browser, etc.

Is there any javascript method or css rule to return the number of lines for a particular p element in a particular browser for a particular screen size?

I mean how can we check the number of lines when the p elemnt is loaded if we want to do something with that number such as store it in a variable or use it in an if statement?

Is there any way this can be done?

Asif Ali
  • 271
  • 1
  • 3
  • 16
  • Possible duplicate - https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i – Sujit Agarwal Sep 29 '18 at 13:43
  • 1
    Calculate the height of a p with one line and then the height of the actual content. Devide and you have the approximate lines. – Hugo Delsing Sep 29 '18 at 13:45
  • 3
    Possible duplicate of [How can I count text lines inside an DOM element? Can I?](https://stackoverflow.com/questions/783899/how-can-i-count-text-lines-inside-an-dom-element-can-i) – Nick Parsons Sep 29 '18 at 13:48
  • A

    element will have a set amount of padding/margin top and bottom, irrespective of the number of lines. - so simple division by the height of a single line paragraph won't really work. I'm not sure why you need the number of lines - it would be a lot easier to get the height, deduct the standard padding/margin amount - and what's left is the text height. You could equate this easily enough to a number of lines, or just save it as a means of comparing the content height of various

    elements.

    – sideroxylon Sep 29 '18 at 14:08

2 Answers2

2

a simple calculation of element height divided by line height can give you the number of lines rendered on actual display.

// 1. get height of element.
// 2. get line height.
// 3. divide 1 by 2 to figure out computed lines.

function countLines(element) {

    let x = $(element).prop('scrollHeight');
    let y = $(element).css('lineHeight');
    y = parseInt(y);

    return x/y;
}
aviya.developer
  • 3,343
  • 2
  • 15
  • 41
1

By counting line breaks it's possible using javascript,check my code below

function lineBreakCount(str){
/* counts \n */
try {
    return((str.match(/[^\n]*\n[^\n]*/gi).length));
} catch(e) {
    return 0;
}
}