Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does newline after pre tag disappear?

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?

like image 701
Reto Gmür Avatar asked Dec 25 '22 08:12

Reto Gmür


1 Answers

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 recommend 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).

like image 191
T.J. Crowder Avatar answered Dec 28 '22 05:12

T.J. Crowder