3

I want to iterate through all HTML elements with a specific class name in TypeScript. I tried:

let elements = [...document.getElementsByClassName("myclass")];

But I get this 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
});

but this only works for the first item. If I use alert(item.innerText) I only receive one alert.

What's the proper way to iterate through a HTMLCollection?

Thank you!

Julius Babies
  • 955
  • 3
  • 6
  • 22
  • Does this answer your question? [For loop for HTMLCollection elements](https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements) – D M Aug 22 '22 at 19:37
  • As I mentioned in the edit, I am not a huge fan of using a `for` loop with an incrementing integer. `for (let item in array)` doesn't work in TypeScript: `TS2488: Type 'HTMLCollectionOf ' must have a '[Symbol.iterator]()' method that returns an iterator.` – Julius Babies Aug 22 '22 at 19:39
  • 1
    You're close with your second attempt. Try `Array.from(document.getElementsByClassName("myclass")).forEach(element => { ... });`. Also, the linked duplicate target recommends `for...let...of` not `for...let...in`. – D M Aug 22 '22 at 19:39
  • Oh, thank you, that worked. (If you post this as an answer I will accept it :) ) – Julius Babies Aug 22 '22 at 19:40
  • I'm not going to post an answer because I believe this is a duplicate question. You could accept the duplicate target tho! :) – D M Aug 22 '22 at 19:41
  • It's not a duplicate, because it's a TypeScript Problem. If I used normal JavaScript I could use `[...document.getElementsWithClassName("className")]` – Julius Babies Aug 22 '22 at 19:57

1 Answers1

2

You will want to use array.from() and then use a forEach on that array. Here is a working codesandbox to look at an example: https://codesandbox.io/s/youthful-wozniak-rs4d70?file=/index.html

let elements = document.getElementsByClassName("myclass");
Array.from(elements).forEach(function (element) {
  element.innerHTML = "Edited";
});
Colin Hale
  • 824
  • 5
  • 11
  • `forEach` exists on `NodeList`, you don't have to use `Array.from` – Konrad Aug 22 '22 at 19:44
  • @KonradLinkowski You are right you can use forEach on a NodeList. However, document.getElementsByClassName returns an HTMLCollection not a NodeList. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – Colin Hale Aug 22 '22 at 19:57