htmldomchild-nodes

what is the first child node of this div element?


What is the first child node of the 'div' element in this example?

I thought it would be the first 'p' element. It seems to be something else though.

<!DOCTYPE html>
<html>
<body>

<div id="myDiv">
<p>my first paragraph</p>
<p>my second paragraph</p>
</div>

<p id="demo1"></p>
<p id="demo2"></p>


<script>
document.getElementById("demo1").innerHTML = document.getElementById("myDiv").childNodes[0];

document.getElementById("demo2").innerHTML = document.getElementById("myDiv").childNodes[1].childNodes[0].nodeValue;


</script>

</body>
</html>


my first paragraph

my second paragraph

[object Text]

my first paragraph

Solution

  • Since there is whitespace at the beginning of the parent it's textNode with whitespace as content. You can check the nodeType property(3 represent text node) for checking node type.

    console.log(document.getElementById("myDiv").childNodes[0].nodeType)
    <div id="myDiv">
      <p>my first paragraph</p>
      <p>my second paragraph</p>
    </div>


    To get only children elements use children property.

    document.getElementById("myDiv").children[0].textContent;
    

    console.log(document.getElementById("myDiv").children[0].textContent)
    <div id="myDiv">
      <p>my first paragraph</p>
      <p>my second paragraph</p>
    </div>