[英]Typescript: Initialize an empty NodeListOf
I am struggling in TS with querySelectorAll
.我在 TS 中苦苦挣扎
querySelectorAll
。 I want to access any HTML element with this selector, no matter if it is a button, input and so on.我想使用此选择器访问任何 HTML 元素,无论它是按钮、输入等。
For querySelector
I did something like this (which works fine):对于
querySelector
我做了这样的事情(效果很好):
function selector(element: HTMLElement, selector: string): HTMLElement | null {
return element.querySelector(selector);
}
const element: HTMLElement | null = selector(document.body, '.my-button');
This is my similar method for querySelectorAll
:这是我对
querySelectorAll
的类似方法:
function selectorAll(element: HTMLElement, selector: string): NodeListOf<HTMLElement> {
return element.querySelectorAll<HTMLElement>(selector);
}
Now my issue is that I can not initialize an empty node list.现在我的问题是我无法初始化一个空节点列表。 For example:
例如:
let buttons: NodeListOf<HTMLElement> = [];
buttons = selectorAll(document.body, 'button');
The compiler says: The property 'item' is missing in type 'never[]' but required in type 'NodeListElement'.编译器说: “never[]”类型中缺少属性“item”,但在“NodeListElement”类型中是必需的。
So what is the correct syntax for initializing an empty NodeListOf
type?那么初始化空
NodeListOf
类型的正确语法是什么?
There is no easy way to create an object with the NodeList
interface other than calling querySelectorAll
and related DOM APIs.除了调用
querySelectorAll
和相关的 DOM API 之外,没有简单的方法可以使用NodeList
接口创建 object。
One alternative is to use array instead of NodeList
.一种替代方法是使用数组而不是
NodeList
。
let buttons: Array<HTMLElement> = [];
buttons = Array.from(selectorAll(document.body, 'button'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.