Asif Ali
Asif Ali

Reputation: 281

How to return number of lines for a p element?

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?

Upvotes: 0

Views: 1657

Answers (2)

aviya.developer
aviya.developer

Reputation: 3613

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;
}

Upvotes: 2

user10142451
user10142451

Reputation:

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;
}
}

Upvotes: 1

Related Questions