为什么一个DIV只有一个孩子,但有三个子节点?

时间:2015-09-22 08:12:17

标签: javascript html

我有两个div看起来像:

<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个子节点,

  1. childNode [0]是#text;
  2. childNode [1]是DIV;
  3. childNode [2]是#text
  4. 为什么有2个#text?谢谢你的任何想法。

2 个答案:

答案 0 :(得分:3)

由于您在<div id="responseframe">之后和第一次</div>之后添加了新行。

如果你把它放在一行将有一个节点:div。

Html:

<div id="responseframe"><div id="oldframe"></div></div>

输出:

-------------Here is the nodes number of reponseframe---------: 1 
-------------Here is the nodes name of reponseframe's child---------: DIV

这是小提琴:http://jsfiddle.net/cassln/t7kec97u/2/

答案 1 :(得分:1)

<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> 属性返回父元素的所有直接子元素节点,包括textNodes,commentNodes。

所以在你的情况下你有:

#text0 #DIV(oldframe) #text1

所以最后我们得到了直接的孩子:Node.children

如果您只想获得直接的elementNode(没有textNodes和commentNodes),则需要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);

select * from movies 
 inner join relationship as r1 on movies.id=r1.movie_id 
inner join relationship as r2 on movies.id=r2.movie_id 
where r1.Taxonomy_id ="xyz" 
and r2.Taxonomy_id="abc"
 GROUP BY movies.id