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 i开发者_如何学Ct.
you could use the javascript split function to count the line breaks.
$('pre').html().split(/\n/).length
better
$('pre').html().match(/\n/)
Using jQuery
$('#preID').text().split('\n').length
using plain javascript
document.getElementById('preID').innerHTML.split('\n').length
example at http://jsfiddle.net/gaby/tdekQ/
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.
精彩评论