You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Uncaught TypeError报错求助:无法读取undefined的style属性

问题解决:Uncaught TypeError: Cannot read properties of undefined (reading 'style')

错误原因

你的for循环条件写错了:i<= list.length。list是通过getElementsByClassName获取的HTMLCollection,它的索引从0开始,最大有效索引是list.length - 1。当i等于list.length时,list[i]是undefined,此时访问undefined.style就会触发类型错误。

修复代码

把循环条件改成i < list.length即可:

//GETELEMENTBYID
// Accessing the H1 tag dynamically and changing the colour

var ht = document.getElementById('hd1');
ht.style.color='white';
ht.style.backgroundColor='grey';

//Changing the text of the contents

var p1 = document.getElementById('para1');
p1.innerText='Java Script is kinda tough';

/* GETELEMENTSBYCLASSNAME
Changing the colour of list items */

var list = document.getElementsByClassName('list1');
console.log(list);
list[0].style.backgroundColor='gray'; // We have to specifically mention the item index for styling, else it'd show error.

for(var i = 0 ; i < list.length; i++){ // 将<=修改为<
    list[i].style.color='white';  
}

额外优化提示

getElementsByClassName返回的是动态HTMLCollection,若不需要DOM变化时自动更新的特性,可将其转为数组处理,之后能用更简洁的数组遍历方法:

var list = Array.from(document.getElementsByClassName('list1'));
list.forEach(item => {
    item.style.color='white';
});

内容的提问来源于stack exchange,提问作者Sanjeev Krishna S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 15:57:16