Sunday, 19 March 2017

javascript - Why do browsers insert 2 linebreaks into an empty body element?



Occasionally whitespace inside HTML matters seriously. Therefore I wanted to know why Chrome as well as Firefox insert 2 linebreaks in an empty body element.




loading a page with






or equally







gives a body with 2 linebreaks in it:



document.body.outerHTML // ↵↵
document.body.firstChild // #text, 2 linefeeds


setting innerHTML or outerHTML to "" or deleting the textnode child give a really empty body



document.body.outerHTML // ""



Why do browser do this magical insertion of the 2 linefeeds?


Answer



You're seeing line breaks from elsewhere in your HTML (before the head, between head and body). If you remove all linebreaks leading up to and after , you won't have any in the body.



The reason is probably largely historical related to tolerating invalid markup, but it's codified now: The full details are in the spec starting here. Notice, for instance, that both the "in head" insertion mode and the "after head" insertion mode process whitespace by inserting the character.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...