我有两个股利看起来像:
<div id="responseframe">
<div id="oldframe">
</div>
</div>
我以为#oldframe DIV是#responseframe的唯一孩子。但是,当我用JavaScript编写此代码时,
var old=document.getElementById("responseframe");
var nodesnumber=old.childNodes.length;
console.log("-------------Here is the nodes number of reponseframe---------: "+nodesnumber);
var nodesname=old.childNodes[i].nodeName;
console.log("-------------Here is the nodes name of reponseframe's child---------: "+nodesname);
控制台告诉我#responseframe有3个子节点,并且
为什么有2个#text?谢谢你的任何想法。
Node.childNodes
属性返回父元素的所有直接子元素elementNode,包括textNodes,commentNodes。
因此,您有:
<div id="responseframe"><!-- this whole space area is considered by html as single space so you got your first #text Node
--><div id="oldframe"><!-- this area is ignored because this is not direct child area of the responseframe
--></div><!-- this whole space area is considered by html as single space so you got your second #text Node
--></div>
所以最后我们有了直接的孩子:#text0 #DIV(oldframe) #text1
。
如果只想获取直接elementNode(没有textNode和commentNodes),则需要Node.children
。
var old=document.getElementById("responseframe");
var nodesnumber=old.children.length;
console.log("-------------Here is the nodes number of reponseframe---------: "+nodesnumber);
var nodesname=old.children[i].nodeName;
console.log("-------------Here is the nodes name of reponseframe's child---------: "+nodesname);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句