提示:Cannot set property 'height' of undefined

Posted on 2019-09-27 11:34  jessie-xian  阅读(1777)  评论(0编辑  收藏  举报
<html>
<head>
<script>
window.onload=function(){
var oUl = document.getElementById("ul1");
var i=0;
for(i=0;i<oUl.childNodes.length;i++){
oUl.childNodes[i].style.height=30+'px';
}
}
</script>
<style type='text/css'>
</style>
</head>
<body>
<ul id='ul1'>
<li>jason</li>
<li>rekken</li>
<li>guo</li>
</ul>
</body>
</html>

运行之后报Cannot set property 'height' of undefined错误

IE下childNodes取得的节点不包括文本节点,而在Chrome或Firefox下得到的节点包括文本节点,具体看下面代码的执行结果:

var oUl = document.getElementById("ul1");
console.log(oUl.childNodes); // [text, li, text, li, text, li, text]

在代码中,当循环childNodes的时候,第一个节点是textNode,不具备style属性,所以会报'undefined';

常见的解决方法有两种:

// 方法一
var oUl = document.getElementById("ul1");
var i=0;
var children = oUl.childNodes;
for(i = 0; i < children.length; i++){
    if (children[i].nodeType === 1) {
        children[i].style.background = 'red';
    }
}
 
// 方法二
var oUl = document.getElementById("ul1");
var i=0;
var children = oUl.children;
for(i = 0; i < children.length; i++){
    children[i].style.background = 'red';
}

两种方法都能达到想要的效果,且解决了报错的问题