I am new to typescript and I'm trying to iterate over a HTMLCollection got by document.getElementsByClassName()
. My code is:
let tag_list = document.getElementsByClassName("...") as HTMLCollectionOf<HTMLLinkElement>;
for (const tag of tag_list) {
//do sth with tag.href
}
But it turns out that "TS2495: Type 'HTMLCollectionOf' is not an array type or a string type." So what is the best way I can do to prevent this error?
The elements can be iterated through by using a normal for loop. The number of elements in the HTMLCollection can be found out by using the length property of the collection. A for loop is then run to the number of elements. Each of the items can be accessed by using square brackets with their respective index.
An HTMLCollection is an array-like collection (list) of HTML elements. The elements in a collection can be accessed by index (starts at 0). The length Property returns the number of elements in the collection.
HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
The elements can be iterated through by using a normal for loop. The number of elements in the HTMLCollection can be found out by using the length property of the collection. A for loop is then run to the number of elements. Each of the items can be accessed by using square brackets with their respective index.
Method 1: Using the for/of loop: The for/of loop is used to loop over values of an iterable object. This includes arrays, strings, nodeLists, and HTMLCollections.
The HTMLCollection contains other properties that may be returned along with the required elements. There are 3 methods that can be used to properly loop through an HTMLCollection. Method 1: Using the for/of loop: The for/of loop is used to loop over values of an iterable object. This includes arrays, strings, nodeLists, and HTMLCollections.
HTMLCollections may look like Arrays and are also technically a list of objects, but they are fundamentally different. 1) If we want to be able to use the .forEach () method, we can turn the HTMLCollection into an Array, then call the method on it.
HTMLCollectionOf<HTMLLinkElement>
is not an array, therefore, you cannot iterate it. So, you need to make it an array
for (const tag of Array.from(tag_list)) {
Hope this help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With