Property 'style' does not exist on type 'Element' in TS
1.报错情况:
当前环境:TS
发生错误的实例:
原因:
通过document.getElementsByClassName
函数返回的类型为HTMLCollectionOf<Element>
,而Element
类型上不存在style
属性。需要通过类型断言
设置正确的类型。
2. 解决
1.使用document.getElementsByClassName
要解决此错误,使用类型断言将元素键入为 HTMLCollectionOf<HTMLElement>
.
const boxes = document.getElementsByClassName(
'box',
) as HTMLCollectionOf<HTMLElement>;
for (let i = 0; i < boxes.length; i++) {
boxes[i].style.backgroundColor = 'salmon';
}
2.使用document.querySelector
要解决此错误,使用类型断言将元素键入为 HTMLElement
.
const box = document.querySelector('#box') as HTMLElement | null;
if (box != null) {
box.style.backgroundColor = 'salmon';
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步