Dyana Putry Dyana Putry - 4 months ago 13
jQuery Question

Removing blank lines in <pre> with javascript?

How all formats of writing html code below can be issued the same result as in the picture?
Remove Blank Lines

HTML:

<pre><code>The text line 1
The text line 2
The text line 3</code></pre>

<pre><code>The text line 1
The text line 2
The text line 3
</code></pre>

<pre><code>
The text line 1
The text line 2
The text line 3
</code></pre>


JS

(function() {
var pre = document.getElementsByTagName('pre'),
pl = pre.length;
for (var i = 0; i < pl; i++) {
pre[i].innerHTML = '<span class="line-number"></span>' + pre[i].innerHTML + '<span class="cl"></span>';
var num = pre[i].innerHTML.split(/\n/).length;
for (var j = 0; j < num; j++) {
var line_num = pre[i].getElementsByTagName('span')[0];
line_num.innerHTML += '<span>' + (j+1) + '</span>';
}
}
})();


Code details can be seen at http://jsfiddle.net/hidyanaputri/sqq2qkon/1/

Bottom line if the first line or the last row is empty it will not appear numbered. Not a problem if there is a blank line in the middle.

Answer

Couldn't you just trim the content of the <code> tags before you number the lines?`

$('pre code').text(function(_,t) { return $.trim(t) })

FIDDLE

It the code contains HTML, just return that as the text instead, as pre tags will display the HTML as text anyway

$('pre code').text(function(_, t) {return $.trim(this.innerHTML)});

FIDDLE

Comments