Type 'HTMLCollectionOf<HTMLCanvasElement>' must have a '[Symbol.iterator]()' method that returns an iterator

这一生的挚爱 提交于 2020-03-04 06:42:28

问题


I am building an Array with

const myCanvas = documen.getElementsByTagName('canvas')

that it's actually working. It returns me something like this:

images: [
0: canvas,
1: canvas,
2: canvas
]

This is for a Typescript project, I want to iterate this Array and transform each image in order to log it.

Like this:

for (const image of myCanvas) {
      console.log(canvas.toDataURL());
    }

(I am not using foreach because it doesn't works with HTMLCollectionOf type)

I need to iterate the HTMLCollection that getElementsByTagName is returning me. The output is Type 'HTMLCollectionOf' must have a 'Symbol.iterator' method that returns an iterator


回答1:


It may be worth checking your TypeScript / definitions version, because I get no errors. I believe the errors relate to some older browsers actually not supporting iteration of the HTML collection, so you could use a traditional for loop.

Both examples shown below:

const myCanvas: HTMLCollectionOf<HTMLCanvasElement> = document.getElementsByTagName('canvas');

for (const image of myCanvas) {
  console.log(image.toDataURL());
}

for (let i = 0; i < myCanvas.length; i++) {
  console.log(myCanvas[i].toDataURL());
}



回答2:


In order to iterate that way you need to set compilerOptions like this:

"compilerOptions": {
        // ...
        "target": "ES6",
        "lib": [
            "DOM",
            "DOM.Iterable",
            "ES6"
        ]
        // ...
    }


来源:https://stackoverflow.com/questions/57621104/type-htmlcollectionofhtmlcanvaselement-must-have-a-symbol-iterator-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!