Reputation: 323
I'm trying to learn JavaScript from the very beginning to understand it.
What I'm trying to do here is to output the nodeTypes of each element found in the <body>
tag. I understand that there are invisible texts between the <body>
's child elements for some unknown reason, which makes the output
3 1 3 1
I put the <script>
tag outside the <body>
tag, but it's still being counted in the for
loop, which resulted the last digit of 1
in the 3 1 3 1
loop sequence. Why? Why is the <script>
tag being forced inside the <body>
tag by the browser?
<html>
<body id = "bodyTest">
<p>Some Text</p>
</body>
<script type="text/javascript">
var c = document.body.childNodes;
var txt = "";
for(var k = 0; k < c.length; k++) {
txt += c[k].nodeType + " ";
console.log(txt);
console.log(c[k].nodeName);
}
alert(txt);
</script>
</html>
Here is the code I am using.
<html>
<body id = "bodyTest">
<p>Some Text</p>
</body>
<script type="text/javascript">
// Code above
</script>
</html>
Upvotes: 0
Views: 74
Reputation: 29916
The html specification has some restriction about which elements can be contained by the root html element. Script is not one of them, so the htmls you showed us are indeed invalid. However browsers will do their best to still process most of the source. For example, you can have a html file without html, head and body, and the browser will still show the page by wrapping the input in body and html tags.
About the invisible nodes: they are text nodes with a single space. By the specification, any whitespace sequence should be treated as a single space, and the whitespace between your elements (spaces, newlines) still count as text. Try this and see what happens:
<html>
<body id="bodyTest">
<p>Some Text</p><script type="text/javascript">
var c = document.body.childNodes;
var txt = "";
for(var k = 0; k < c.length; k++) {
txt += c[k].nodeType + " ";
console.log(txt);
console.log(c[k].nodeName);
}
alert(txt);
</script>
</body>
</html>
Upvotes: 1
Reputation: 3937
Your browser is correcting your poorly formed HTML by putting the <script>
in the closest element that is valid within an <html>
element, the <body>
.
Upvotes: 0
Reputation: 44831
That's not valid HTML. The <html>
tag can only contain <head>
and <body>
tags, not <script>
.
See the specification:
Permitted contents
One head element, followed by one body element
When your browser encounters broken HTML, it tries to fix it. In this case, that means treating your <script>
tag as though it was in the <body>
.
Upvotes: 7