Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the lines of a PRE element using jQuery

How can I count how many lines of text a <pre> tag contains?

I want to append a absolute div with line numbers next to it.

like image 632
Alex Avatar asked Apr 04 '11 23:04

Alex


People also ask

How do I count text lines inside a DOM element?

To count number of text lines inside DOM element, we will use the following approach. Obtain the total height of content inside the DOM element. Obtain the height of one line. By dividing the total height of the content by the height of one line, you get the total number of lines inside the element.

How do I count the number of lines in a div?

To get the number of lines in an element, we can divide the element's height by its line-height. Then we can do the computation by writing: const el = document. querySelector('div'); const divHeight = +el.

How do I get the number of lines in JavaScript?

To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);


1 Answers

you could use the javascript split function to count the line breaks.

$('pre').html().split(/\n/).length

better

$('pre').html().match(/\n/)
like image 131
mjspier Avatar answered Sep 19 '22 14:09

mjspier