<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script>
window.onload = function(){
var oUl = document.getElementById("ul1");
alert(oUl.childNodes.length);
// for(var i=0; i<oUl.childNodes.length; i++){
// oUl.childNodes[i].style.background = "red";
// }; 错误写法,因为childsNode会同时选取文本节点和元素节点
/* for(var i=0; i<oUl.childNodes.length; i++){
if(oUl.childNodes[i].nodeType==1){
oUl.childNodes[i].style.background = "red";
} nodeType==1,则是元素节点;nodeType==3,则是文本节点
};*/
alert(oUl.children.length);
for(var i=0; i<oUl.children.length; i++){ //涉及到具体某一个元素时,才用[i]
oUl.children[i].style.background = "blue";
}
}
</script>
</head>
<body>
<ul id="ul1">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
022 DOM子节点 childNodes nodeType children
最新推荐文章于 2021-06-24 17:53:19 发布