Quiero iterar a través de todos los elementos HTML con un nombre de clase específico en TypeScript. Lo intenté:
let elements = [...document.getElementsByClassName("myclass")]; Pero recibo este error TS2488: Type 'HTMLCollectionOf ' must have a '[Symbol.iterator]()' method that returns an iterator.
let elements = document.getElementsByClassName("myclass"); Array.prototype.forEach.call(elements, function (item:HTMLElement) { // do stuff with the item }); pero esto solo funciona para el primer elemento. Si uso alert(item.innerText) solo recibo una alerta.
¿Cuál es la forma correcta de iterar a través de HTMLCollection ?
¡Gracias!
Querrá usar array.from() y luego usar forEach en esa matriz. Aquí hay un codesandbox de trabajo para ver un ejemplo: https://codesandbox.io/s/youthful-wozniak-rs4d70?file=/index.html
let elements = document.getElementsByClassName("myclass"); Array.from(elements).forEach(function (element) { element.innerHTML = "Edited"; });