2013-05-08 63 views
1

this link返回子节点的列表。在我的测试中,这似乎忽略了文本节点。它是否正确?elementNodeReference.children不检测文本节点?

让我感到困惑的是firstChild的作品,但儿童名单是零。

测试在Firefox 20.0.1。

这里是我的测试代码:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<title></title> 
<script> 

function checktable() { 
    var mytable = document.getElementById("mytable"); 

    var cells = mytable.rows[0].cells; 

    for (var i = 0; i < cells.length; i++) { 
     console.log("firstChild.nodeValue:", cells[i].firstChild.nodeValue); 
     console.log("firstChild.data:",cells[i].firstChild.data); 
     console.log("children.length:",cells[i].children.length); 
    } 
} 


function checkdiv() { 
    var mydiv = document.getElementById("mydiv"); 
    console.log("firstChild.nodeValue:", mydiv.firstChild.nodeValue); 
    console.log("firstChild.data:",mydiv.firstChild.data); 
    console.log("children.length:",mydiv.children.length); 
} 
</script> 
<style> 
</style> 
</head> 

<body> 

<table id="mytable"> 
<tr> 
<td>Blob</td> 
<td>Blab</td> 
<td><a href="http://stackoverflow.com">Link</a></td> 
</tr> 
</table> 

<div id="mydiv"> 
Blib 
</div> 

<button onclick="checktable()">Check table</button> 
<button onclick="checkdiv()">Check div</button> 

</body> 
</html> 

回答

1

你想.childNodes,不.children

前者是Node的方法,并列出了子节点。后者是Element的一种方法,因此列出了子元素,这在某些情况下是可取的。