如何从 DOM 中输入 HTMlElement[] ?

问题描述 投票:0回答:1

在打字稿中,我需要收集页面的所有 div 并使用下面的代码

const getHTMLElement() : HTMLElement[] {
  const doc = document.body.children;
  const listL HTMLElement[] = [];
      for (let c of Array.from(doc)) {
          if (c.tagName === 'DIV' && c.textContent !== '') {
              list.push(c);
          }
      }
  console.log({list})
}

但它在

.push(c)
线上给出了ts错误

“Element”类型的参数不可分配给“HTMLElement”类型的参数。

这里出了什么问题?

尝试过

querySelectorAll()

const getHTMLElement = (): HTMLElement[] {
  const doc = document.querySelectorAll('body');
  const list = [];
      for (let c of Array.from(doc)) {
          if (c.tagName === 'DIV' && c.textContent !== '') {
              list.push(c);
          }
      }
  console.log({list})
}

虽然这不会给出任何类型错误,但这里

c
的类型是
HTMLBodyElement
这似乎我不正确

那么获取

HTMLElement[]
类型列表的写入方式是什么

typescript typescript-typings
1个回答
0
投票

如果您确实想要一组顶级

div
,请使用
Array.from(document.querySelectorAll('body > div'))

© www.soinside.com 2019 - 2024. All rights reserved.