Looking to loop through the results from
document.getElementsByTagName("...");
This method returns an HTMLCollection
, not an array. Therefore, using forEach
directly is not possible.
One way to achieve this is as follows:
let elements = document.getElementsByTagName("...");
for (var i = 0, m = elements.length; i < m; i++) {
let element = elements[i];
}
A similar question exists for javascript: For loop for HTMLCollection elements
Recent updates show that modern browsers now support:
var list = document.getElementsByClassName("events");
for (let item of list) {
log(item.id);
}
However, there seems to be a typescript compiler error:
error TS2495: Type 'NodeListOf<HTMLParagraphElement>' is not an array type or a string type.
Despite this, the code transpiles to valid Javascript with proper functionality. The compiled output looks like this:
var elements = main_div.getElementsByTagName("p");
for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
var element = elements_1[_i];
}
It's reassuring to see that the generated code remains compatible even with older browsers. Yet, it would be ideal to resolve the error message.
The compilerOptions set are as follows:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"rootDir": "src",
"lib": [
"es2015",
"dom"
]
}
}
Attempts were made to modify the lib options in search of a solution, considering that the feature originated in ES6 and underwent revisions. Testing different ecmascript versions did not yield a successful configuration.