childNodes:
标准的,它返回指定元素的子元素集合,包括html节点,所有属性,文本。可以通过nodeType来判断是哪种类型的节点,只有当nodeType==1时才是元素节点,2是属性节点,3是文本节点。如果代码中有换行、空格就会增加文本节点,这样用它来返回真正的子节点就会不准确,具体见下面的例子。
除了IE9和Firefox,其他浏览器都支持通过childNodes[i]获取第i个子节点。
children:
非标准的,它返回指定元素的子元素集合。经测试,它只返回html节点,甚至不返回文本节点。且在所有浏览器下表现惊人的一致。因此如果想获取指定元素的第一个html节点,可以使用children[0]来替代上面的getFirst函数。需注意children在IE中包含注释节点。
返回指定元素的子元素集合,只包括元素节点,不包括文本节点。
除了IE9和Firefox,其他浏览器都支持通过children[i]获取第i个子节点。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="test">
第一个子节点(且为文本节点)
<div>第二个子节点(同时是第一个HTML元素节点)</div>
第三个子节点(也是子节点)
<div>第四个子节点(同时也是第二个HTML元素节点)</div>
<div>第五个子节点(同时也是第三个HTML元素节点),但我面前有个回车(即空节点)
<div>我是第五个子元素的一个子节点</div>
</div>
<p id="ptag">this is a p tag.</p>
</div>
<script type="text/javascript">
var test = document.getElementById('test');
for (var i = 0; i < test.childNodes.length; i++) {
console.log(test.childNodes[i]);
if (i == test.childNodes.length - 1) {
console.log('test.childNodes.length: ', test.childNodes.length);
}
}
for (var j = 0; j < test.children.length; j++) {
console.log(test.children[j]);
if (j == test.children.length - 1) {
console.log('test.children.length: ', test.children.length)
}
}
</script>
</body>
</html>
结果截图:
输出界面:
控制台:(请仔细观察两种输出方式的数量)