我正在使用DOM来检索我的元素节点的子节点,这些节点的类名是' main'如下面的html代码段所示。 在我看来,父元素下有9个子元素。但我很惊讶 由子节点值。有没有人对
下面的输出有解释<section class="main">
<h2>Page Title</h2>
<h3>Article Heading</h3>
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Third Paragraph</p>
<p>Fourth Paragraph</p>
<h3>Instructions</h3>
<p>Fifth Paragraph</p>
<p>Sixth Paragraph</p>
</section>
JS代码:
var articleHeadElemNode = document.querySelector(".main");
console.log(articleHeadElemNode.childElementCount);
for (i =0; i<articleHeadElemNode.childElementCount ; i++ )
console.log(articleHeadElemNode.childNodes[i]);
最终输出:
9
#text
<h2>Page Title</h2>
#text
<h3>Article Heading</h3>
#text
<p>First Paragraph</p>
#text
<p>Second Paragraph</p>
#text
其余段落在哪里?我设法使用了检索元素 document.querySelector(&#34; .main&gt; h3&#34;)或使用querySelectorAll但我对这里发生的事情的逻辑解释感兴趣?
答案 0 :(得分:1)
最好将Element.children
用于子元素。 Element.children
仅返回元素节点子节点,而Node.childNodes
将返回所有节点子节点:
for(var i = 0; i < articleHeadElemNode.childElementCount; i++)
console.log(articleHeadElemNode.children[i]);
答案 1 :(得分:1)
那是因为您正在阅读childElementCount
,其中包含nodeType
1
的子节点数,并且您正在读取循环中的所有childNodes
,这也会返回{ {1}} textNode
nodeType
。您应该在循环中使用3
属性而不是children
。