Typescript - 如何迭代 HTMLCollection

Evi*_*ian 6 typescript

我是打字稿的新手,我正在尝试遍历 .html 获得的 HTMLCollection document.getElementsByClassName()。我的代码是:

let tag_list = document.getElementsByClassName("...") as HTMLCollectionOf<HTMLLinkElement>;
for (const tag of tag_list) {
    //do sth with tag.href
}
Run Code Online (Sandbox Code Playgroud)

但结果是“TS2495:Type 'HTMLCollectionOf' 不是数组类型或字符串类型。” 那么我能做些什么来防止这个错误呢?

Ngu*_*ien 6

HTMLCollectionOf<HTMLLinkElement>不是数组,因此,您不能对其进行迭代。所以,你需要把它变成一个数组

for (const tag of Array.from(tag_list)) {
Run Code Online (Sandbox Code Playgroud)

希望这有帮助