Reputation: 3
I'm in an entry level javascript course and am studying our Document Object Model section and I am trying to understand the reason why the script below has no value, could someone explain it a little?
<!DOCTYPE html>
<html>
<body id="bdy">
<h1 id="id00">Test 1</h1>
<h1 id="id01">Test2</h1>
<p id="id02"></p>
<script>
document.getElementById("id02").innerHTML = document.getElementById("bdy").childNodes[0].nodeValue;
</script>
</body>
</html>
Upvotes: 0
Views: 167
Reputation: 177786
Because the childnode is not what you think it is. You need to skip empty textnodes and you likely want to access the textContent of the node
Read more here: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace_in_the_DOM
And here: nodeValue vs innerHTML and textContent. How to choose?
for (var i = 0; i < document.getElementById("bdy").childNodes.length; i++) {
console.log(i, document.getElementById("bdy").childNodes[i].textContent)
}
<body id="bdy">
<h1 id="id00">Test 1</h1>
<h1 id="id01">Test2</h1>
<p id="id02"></p>
</body>
This might be what you meant to do:
document.getElementById("id02").innerHTML = document.getElementById("bdy").children[0].textContent;
<body id="bdy">
<h1 id="id00">Test 1</h1>
<h1 id="id01">Test2</h1>
<p id="id02"></p>
</body>
Upvotes: 1