typescript for loop over HTMLCollection

Example usage:

const inputs = document.getElementsByTagName("input");
for (let index = 0; index < inputs.length; index++) {
  const input = inputs.item(index);
}

To get rid of the error message, you can add the list as any type. Typescript difference from JavaScript is the Type. Therefore, It's best practice to add the type to your variable. For your reference, I add the any type:

var list: any = document.getElementsByClassName("events");
for (let item of list) {
    console.log(item.id);
}

Actually, this is a typical "contextual typing". Contextual typing occurs when the type of an expression is implied by its location. For the code above to give the type error, the TypeScript type checker used the type of the document.getElementsByClassName("events") to infer the type of the ForLoop function. If this function expression were not in a contextually typed position, the list would have type any, and no error would have been issued.

If the contextually typed expression contains explicit type information, the contextual type is ignored.

Contextual typing applies in many cases. Common cases include arguments to function calls, right hand sides of assignments, type assertions, members of object and array literals, and return statements. The contextual type also acts as a candidate type in best common type.[From TypeScript Document]


You can convert it to an array if you want to use forEach

const elements: Element[] = Array.from(document.getElementsByTagName("..."));
elements.forEach((el: Element) => {
    // do something
})

The typescript compiler supports this after specifying an extra flag, downlevelIteration:

{
    "compilerOptions": {
        "target": "es5",
        "downlevelIteration": true
    }
}

However, this will not only remove the error, it will also change the compiler output. This input typescript:

function compileTest(){
  let elements = document.getElementsByTagName("p");
  for(let element of elements){
    console.log(element);
  }
}

is compiled to this javascript:

function compileTest() {
    var e_1, _a;
    var elements = document.getElementsByTagName("p");
    try {
        for (var elements_1 = __values(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) {
            var element = elements_1_1.value;
            console.log(element);
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (elements_1_1 && !elements_1_1.done && (_a = elements_1.return)) _a.call(elements_1);
        }
        finally { if (e_1) throw e_1.error; }
    }
}

Tags:

Typescript