Warning: 不要在生产环境中使用该属性,由于其作用基本可以被element.children.length所取代,所以在未来版本的Gecko中,该属性可能会被删除. 查看
概述
childElementCount属性返回当前元素的子元素个数,而不是子节点个数. 只有当一个节点的nodeType属性为1(Node.ELEMENT_NODE==1)时,它才是元素节点 .文本节点和注释节点不属于元素节点.
如果你需要获取一个元素的子元素而不是子元素个数, 请使用element.children属性.
注意:在IE9之前,element.children会包含一个元素的子元素节点和子注释节点.在IE9之后或者其他浏览器中, 只包含子元素节点.
另外,由于IE9之前的版本不支持childElementCount属性, 所以如果考虑兼容性的话,请使用element.children.length(并且需要判断nodeType是否为1)来代替childElementCount属性.
语法
var elCount = elementNodeReference.childElementCount;
该属性为只读属性.
例子
下例演示了一个元素节点的childElementCount属性以及children属性的用法.
<head>
<script type="text/javascript">
function GetChildCount () {
var container = document.getElementById ("container");
var childCount = 0;
//如果支持childElementCount属性
if ('childElementCount' in container) {
childCount = container.childElementCount;
}
else {
//如果支持children属性,IE6/7/8
//译者注:没有判断nodeType是否为1,可能包含注释节点.
if (container.children) {
childCount = container.children.length;
}
else { //,如果都不支持,Firefox 3.5之前版本
var child = container.firstChild;
while (child) {
if (child.nodeType == 1 /*Node.ELEMENT_NODE*/) {
childCount++;
}
child = child.nextSibling;
}
}
}
alert ("The number of child elements is " + childCount);
}
</script>
</head>
<body>
<div id="container" style="width:300px; background-color:#a0d0e0;">
Some text inside the container.
<input type="text" size="40" value="a child element of the container" />
<div>
<div>a descendant element of the container</div>
<div>another descendant element of the container</div>
</div>
</div>
<br /><br />
<button onclick="GetChildCount ();">Get the number of container's child elements</button>
</body>
浏览器兼容性
| Feature | Firefox (Gecko) | Chrome | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | Unknown (3) | (Yes) | 9.0 | (Yes) | (Yes) |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |
规范
相关链接