childNodes和nodeType

来源:互联网 发布:帝国cms ajax提交表单 编辑:程序博客网 时间:2024/05/17 06:03
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script>//DOM节点window.onload=function() {var oUl=document.getElementById('ul1');alert(oUl.childNodes.length);   //存放Ul的子节点的数组//将弹出11//把空的文本节点算作子节点。IE6-8没有问题for(var i=0; i < oUl.childNodes.length; i++) {//oUl.childNodes[i].style.background='red';//出错,文本节点没有background属性//nodeType,告知节点类型//nodeType==3 -> 文本节点//nodeType==1 -> 元素节点if (oUl.childNodes[i].nodeType == 1) {oUl.childNodes[i].style.background='red';}}}</script></head><body><ul id="ul1"><li></li><li></li><li></li><li></li><li></li></ul></body></html>


更好的方式是使用children属性

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><script>//DOM节点window.onload=function() {var oUl=document.getElementById('ul1');alert(oUl.children.length);}</script></head><body><ul id="ul1"><li></li><li></li><li></li><li></li><li></li></ul></body></html>
注意:子节点只算第一层的


0 0