首页 > 其他分享 >Property 'style' does not exist on type 'Element' in TS

Property 'style' does not exist on type 'Element' in TS

时间:2022-10-11 20:55:36浏览次数:47  
标签:box style getElementsByClassName TS Element document

1.报错情况:

当前环境:Vue3 + 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';
}

标签:box,style,getElementsByClassName,TS,Element,document
From: https://www.cnblogs.com/fuct/p/16782521.html

相关文章

  • FusionCharts的使用方法
    一、简介Ø FusionCharts 是InfoSoft Global 公司的一个产品,InfoSoft Global 公司是专业的Flash 图形方案提供商,他们还有几款其他的,基于Flash 技术的产品,都非常的......
  • 前端_vue3引入Element-plus
    element-plus官网:https://element-plus.gitee.io/zh-CN/component/button.html1、安装element-plusnpminstallelement-plus-D2、在index.js中导入element-plusim......
  • Element UI-实现树形控件单选
    ElementUI-实现树形控件单选1.单选功能elementui中的树形可以设置checkbox,但是不能设置radio的单选功能但官方提供了自动勾选方法:想实现单选只需要给node增加点......
  • elementUI Tree 树形控件实现单选+获取树形控件单选框勾选内容
    elementUITree树形控件实现单选+获取树形控件单选框勾选内容  html部分<el-tree:data="data"show-checkbox......
  • Using Bash shell scripts for function testing
    功能测试是软件开发的一个关键部分--而已经装入Linux的Bash可以帮您轻而易举地完成功能测试。在本文中,AngelRivera将说明如何运用Bashshell脚本通过行命令来执......
  • OutputStream详解
    我们都知道流分为字节流和字符流 输出流又分:字节输出流,字符输出流 输入流又分:字节输入流,字符输入流/*在java中OutputStream表示字节输出流,可以将java程序中的数据写到......
  • CMakeLists.txt中打印所有变量
    一、打印可见变量及其值get_cmake_property(_variableNamesVARIABLES)foreach(_variableName${_variableNames})message(STATUS"${_variableName}=${${_variabl......
  • Vue项目中使用v-charts
    v-charts官网地址​​https://v-charts.js.org​​安装依赖打开命令行,输入vueui,打开可视化界面echarts依赖>安装依赖>运行依赖>echartsv-charts依赖>安装依赖>运行依赖>v......
  • antsword入门级攻击——一句话木马
    最近接触到木马攻击,打算用antsword来测试。https://github.com/AntSwordProject/antSword是官网地址,里面有链接到说明文档https://www.yuque.com/antswordproject/antswo......
  • PCIe物理层LTSSM状态机解析
    在PCIe链路可以正常工作之前,需要对PCIe链路进行链路训练,在这个过程中,就会用LTSSM状态机。LTSSM全称是LinkTrainingandStatusStateMachine。这个状态机在哪里呢?它就在P......