如何为 HTMLCollectionOf 或 NodeCollection 设置 css 样式?
let items = document.querySelectorAll('.pac-item') as NodeListOf<HTMLElement>;
谢谢大家! 我的失败...那是元素的集合...通过迭代解决了它
var items:any = document.getElementsByClassName('pac-item');
for (let i = 0; i < items.length; i++) {
let element = items[i];
element.style.background = '#2B2B2B';
element.style.color = '#DEDEDE';
}
打字稿定义表明
HTMLCollectionOf
是 HTMLCollection 的扩展,您需要迭代它才能访问各个元素。
interface HTMLCollectionOf<T extends Element> extends HTMLCollection {
item(index: number): T;
namedItem(name: string): T;
[index: number]: T;
}
我希望这有帮助。 :)
您正在使用
HtmlCollectionOf
,所以它是一个集合,并且一个集合有很多项目。因此 items.style.background
不起作用,因为它属于 HtmlElement
。
换句话说,您必须循环遍历集合才能应用于每个
HtmlElement
。或者您可以申请如下所示的特定项目,我认为这就是您想要做的
items[0].style.background = '#2B2B2B';