(NOTE: This question isn't the same as the similar one above, as it is about differences between attached and detached DOM trees.)
A simple bit of HTML containing a DIV with no whitespace between its elements:
<!DOCTYPE html>
<html>
<body>
<div><h1>The Title</h1><p>A paragraph.</p><p>A second paragraph.</p></div>
</body>
<script type="text/javascript">
const div = document.querySelector("div");
console.log(div.innerText);
const clone = div.cloneNode(true);
console.log(clone.innerText);
document.body.appendChild(clone);
console.log(clone.innerText);
</script>
</html>
I output innerText
to the console three times.
The first time is that of the original DIV:
The Title
A paragraph.
A second paragraph.
The second is that of the cloned DIV, which I would expect to be the same, but is:
The TitleA paragraph.A second paragraph.
The third is again that of the cloned DIV, but after it has been added to the document, now what I would expect it to be:
The Title
A paragraph.
A second paragraph.
Why is the spacing different when it is not part of the document?