Reputation: 711
<div>
<h1>Heading
The first thing in the DOM after the div
is a text node, rather than the h1
element. Why does the DOM include this?
(I realise I can select the h1
with firstElementChild
rather than firstChild
, I'm just wondering why the text node is there at all.)
If I apply the style rule h1:first-child {font-size: 600%;}
it affects the heading, so I assume the "CSS DOM" (if that's a thing) ignores this white space.
Perhaps it has something to do with white-space: pre;
-if you ever apply this dynamically the DOM has to be ready? But that doesn't seem to fully explain it.
Upvotes: 1
Views: 309
Reputation: 82986
The variations in white-space handling ought to be reason enough, but since you've already rejected that as unsatisfactory, I'll give you a different example.
Suppose the markup is this:
<section class="test">
<b>My</b><div>
<h1>Heading</h1>
</div>
</section>
If we assume that the all white space text node between the <div>
start tag and the <h1>
start tag is discarded, then that would be identical to
<section class="test">
<b>My</b><div><h1>Heading</h1>
</div>
</section>
Now see what happens if we add this CSS:
.test * {
display:inline;
}
.test * {
display:inline;
/* The below property just helps
with visibility of the issue */
font: 400 1em monospace;
}
<section class="test">
<b>My</b><div>
<h1>Heading</h1>
</div>
</section>
<section class="test">
<b>My</b><div><h1>Heading</h1>
</div>
</section>
Instead of
My Heading
we get
MyHeading
So clearly that all white-space text node is necessary and can't be discarded.
Upvotes: 2