人生人山人海人来人往,自己自尊自爱自由自在。|

青柠i

园龄:4年3个月粉丝:11关注:1

2022-10-11 20:48阅读: 174评论: 0推荐: 0

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';
}
posted @   青柠i  阅读(174)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起