0

我是 Angular 的新手,我正在尝试遍历一个 html 集合,以便我可以获得每个元素的 id 等属性,但即使在获得集合的数组表示后它似乎也不起作用下面的代码。我正在使用打字稿来构建一个角度应用程序。有什么解决办法吗?还是我做错了什么?

this.customElements = Array.from(
      document.getElementsByClassName('custom-elem')
    );

    this.customElements.forEach(element => {
      console.log(element);
    });
4

1 回答 1

1

您不必从 HTMLCollection 创建新数组。getElementsByClassName()默认情况下,函数返回所有子元素的类数组对象。所以以下应该工作:

this.customElements = document.getElementsByClassName('custom-elem');

for (const element in this.customElements) {
  console.log(element);
}

工作示例:Stackblitz

于 2020-02-20T12:13:41.343 回答