Alex
Alex

Reputation: 68450

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.

Upvotes: 7

Views: 4008

Answers (3)

Jeff B
Jeff B

Reputation: 30099

This will work as long as you don't have any <br> tags in your <pre> element:

var numlines = $('#mypreelement').text().match(/\n\r?/g).length + 1;

Example: http://jsfiddle.net/jtbowden/3QThm/

You can handle the <br> tags by counting them separately:

var pretext = $('#mypreelement').html();
var numlines = pretext.match(/\n\r?/g).length + 1;
numlines += $('#test br').length;

Example: http://jsfiddle.net/jtbowden/3QThm/2/

Other tags in the <pre> will cause you headaches.

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

Using jQuery

$('#preID').text().split('\n').length

using plain javascript

document.getElementById('preID').innerHTML.split('\n').length

example at http://jsfiddle.net/gaby/tdekQ/

Upvotes: 3

mjspier
mjspier

Reputation: 6526

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

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

better

$('pre').html().match(/\n/)

Upvotes: 9

Related Questions