in my javascript the nodeType property return 3 for the first child node at index 0
document.getElementById("p1").innerHTML = document.getElementById("div1").childNodes[0].nodeType
<!--this is comment-->
<div id="div1">
<p id="p1"></p>
<h1 id="h1">this is header</h1>
<button onclick="func1()">header will be Smart</button>
<button onclick="func2()">header will be Idiot</button>
<h2 id="h2">header 2</h2>
</div>
the reason behind it and the solution for this
Harry Makvana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Because the first child node in #div1
is a text node (nodeType === 3
) consisting of whitespace (a newline). If you changed your HTML to <div id="div1"><p id="p1"></p>
(notice there’s no newline), the first child node would be the p
element (nodeType === 1
).
You can look at this in the element inspector in your browser’s devtools: Right-click the text, choose Inspect (or Inspect Element) from the context menu, and look at the DOM.
1