删除<pre> with javascript?

时间:2016-07-28 20:18:33

标签: javascript jquery html css regex

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.

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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>

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

您以前的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<-- line break here
</code></pre>

<pre><code><-- line break here
The text line 1
The text line 2
The text line 3<-- line break here
</code></pre>