Javascript 中childNodes和children的区别

时间:2021-02-07 03:51:31
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
//childNodes 我很少用,感觉用的不是很方便
//window.onload = function () {
// var oUl = document.getElementById("ul");
// for (var i = 0; oUl.childNodes.length; i++) {
// //nodeType=1,元素节点
// //nodeType=3,文本节点
// if (oUl.childNodes[i].nodeType == 1) {
// oUl.childNodes[i].style.background="red";
// }
// }
//} window.onload = function () {
var oU = document.getElementById("ul1");
for (var i = 0; i < oU.children.length; i++) {
//children 只包括元素节点,不包括文本节点
oU.children[i].style.background = "red";
}
}
</script>
</head>
<body>
<ul id="ul1">
<li></li>
<li></li>
</ul>
</body>
</html>
//children  只包括元素节点,不包括文本节点  childNodes既包括元素节点,又包括文本节点

可以通过alert(oU.children.leght);和alert(OUl.childNodes.length);进行比较