admin管理员组

文章数量:1406751

Why does a new line immediately following a <pre> tag not appear in the DOM?

<html>
<body>

<div id="mydiv">
hello
div
world
</div>

<pre id="mypre">
hello
pre
world
</pre>

<script>
alert("div content: "+document.getElementById("mydiv").innerHTML)
alert("pre content: "+document.getElementById("mypre").innerHTML)
</script>

</body>
</html>

Shows that unlike the line break after the div-tag the line break after the pre-tag doesn't seem to be in the dom. Also the innerHTML of the whole body doesn't show a line break after the pre-tag.

Is there any way to find out in JS if the original HTML document contains a line break after the <pre> or not?

Why does a new line immediately following a <pre> tag not appear in the DOM?

<html>
<body>

<div id="mydiv">
hello
div
world
</div>

<pre id="mypre">
hello
pre
world
</pre>

<script>
alert("div content: "+document.getElementById("mydiv").innerHTML)
alert("pre content: "+document.getElementById("mypre").innerHTML)
</script>

</body>
</html>

Shows that unlike the line break after the div-tag the line break after the pre-tag doesn't seem to be in the dom. Also the innerHTML of the whole body doesn't show a line break after the pre-tag.

Is there any way to find out in JS if the original HTML document contains a line break after the <pre> or not?

Share asked May 31, 2014 at 11:38 Reto GmürReto Gmür 2,6572 gold badges21 silver badges27 bronze badges 1
  • 1 Excellent job including the SSCCE. Nice one. – T.J. Crowder Commented May 31, 2014 at 11:50
Add a ment  | 

2 Answers 2

Reset to default 8

Because that's what the spec says to do:

Note: In the HTML syntax, a leading newline character immediately following the pre element start tag is stripped.

So if you want that newline there, somewhat counter-intuitively you have to add an extra one: Example

<pre id="mypre">

hello
pre
world
</pre>

Side note: I strongly remend always including a doctype, even in short examples like the one in your question. It can make a difference (although I don't think it does in this case).

From the specification of <pre>:

Note In the HTML syntax, a leading newline character immediately following the pre element start tag is stripped.

I think this is done so you don't have to write:

<pre>Some text
some more
and more
</pre>

to avoid an extra line break at the beginning. You can write:

<pre>
Some text
some more
and more
</pre>

This is useful if you're using <pre> to line up columns, since the first format doesn't allow you to line up the first line properly.

If you want an extra newline at the beginning of your preformatted text, put a blank line after the tag:

<pre id="mypre">

hello
pre
world
</pre>

本文标签: javascriptWhy does newline after pre tag disappearStack Overflow