Difference between javascript .childNodes & .child

2019-04-07 13:52发布

问题:

I have been working with javascript for a week now. I am currently working on making things work/change through nodes. But I have been noticing something strange, well for an unskilled javascripter it is.

I have a structure in my site like this:

<html>

<head>
    <title>....</title>
    <link/>
    <script></script> 
</head>

<body>
    <div 1>
        <div 2></div>  
    </div>
</body>
</html> 

When I am trying to find a childnode with the next function:

var headerBox = document.body.childNodes;
var txt = "";

for (var x = 0; x < headerBox.length; x ++) {
txt =txt+"Childnode["+x+"]: "+headerBox[x].localName+" ("+headerBox[x].className+")<br>";
}

var x = document.getElementById(box);
x.innerHTML = txt;

I get a list with a couple of undefined "NULL" coupled with the reali DIV's

But when I simply change the "document.body.childNodes" to "document.body.children" everything comes uit perfectly, the "NULL" values even change.

What I am wondering is what does the "NULL" values represent in the HTML file, since there are no elements at where the "NULL" value is standing. In my head it is giving me a representation of something that is not there, visible, but yet it is...

Could anyone please explain to me what is going on?

Ps: I am sorry for maybe reposting this but I couldn't find a suitable other question regarding this matter!

Pss: Found a repost (What is the difference between children and childNodes in JavaScript?). But it is not answering why it still recognizes unseen childnodes as undefined.

回答1:

childNodes will give you all kinds of nodes while children will give you only element nodes. You can use nodeType to check what kind of node the current node is:

document.body.childNodes[0].nodeType

This will give you an integer:

1   ELEMENT_NODE
2   ATTRIBUTE_NODE
3   TEXT_NODE
4   CDATA_SECTION_NODE
5   ENTITY_REFERENCE_NODE
6   ENTITY_NODE
7   PROCESSING_INSTRUCTION_NODE
8   COMMENT_NODE
9   DOCUMENT_NODE
10  DOCUMENT_TYPE_NODE
11  DOCUMENT_FRAGMENT_NODE
12  NOTATION_NODE

As you can see, using childNodes will give you a list, that contains text nodes (even if they are filled with whitespaces), comments and all kinds of other node types, you probably don't have to worry too much about.