Reputation: 5492
I have a feeling that this might have something to do with object reference but here it is:
I have following code:
<html>
<head>
<script type="text/javascript">
console.log(document.getElementsByTagName("html"));
console.log(document.getElementsByTagName("html")[0].lastChild);
</script>
</head>
<body><h1>Hello</h1></body>
</html>
In the console, when I expand the first collection returned I can see that it has body as its child node(lastChild) even when the body element has not been parsed yet. But the in the second object it shows the head
tag which is as expected.
Now, while posting this question here, I created this pen but in there the second console is the body tag and not the head.
So, Why the first console statement is showing body in html? or does it has to do something with browsers? Thanks
Upvotes: 3
Views: 102
Reputation: 4281
getElementsByTagName
will give you a live HTMLCollection. This means, when the underlying DOM changes, so does the live collection returned by the function.
An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
So initially, at the time the logging happens, the body tag is still not parsed. If you could check the console output before the body was parsed, you wouldn't see it there.
But when you actually get to check the HTMLCollection in the console, body is already parsed and therefore is shown (since, again, HTMLCollection is live).
If you want to "break" the live connection, you can cast your HTMLCollection into a standard Array using the array spread operator:
const collection = [...liveCollection];
And obviously, the second console.logprints the head tag because by the time it was logged, it was indeed the last child.
FYI
Other common DOM query functions like getElementsByClassName
give you live collections as well.
Upvotes: 1
Reputation: 1007
As @scarySize mentioned, when you log the html tag on the first console.log
, it actually logs the live HTMLCollection.
So initially, at the time the logging happens, the body tag is still not parsed. So if you could check the console output before the body was parsed, you wouldn't see it there.
But when you actually get to check the HTMLCollection in the console, body is already parsed and therefore is shown (since, again, HTMLCollection is live).
And obviously, the second console.log
prints the head tag because by the time it was logged, it was indeed the last child.
Upvotes: 1