Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through HTMLElements with specific class in TypeScript?

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!

like image 726
Julius Babies Avatar asked Oct 27 '25 08:10

Julius Babies


1 Answers

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";
});
like image 150
Colin Hale Avatar answered Oct 28 '25 23:10

Colin Hale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!