Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate through elements with 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thank you!

>Solution :

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";
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading