在打字稿中,我需要收集页面的所有 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[]
类型列表的写入方式是什么
如果您确实想要一组顶级
div
,请使用Array.from(document.querySelectorAll('body > div'))