First, the code you are after:
const cnElems = document.getElementsByClassName("cn");
for (let i = 0; i < cnElems.length; i++) {
const e = cnElems[i];
if (e instanceof HTMLElement) {
e.style.height = "10px";
}
}
Then, an explanation... There are two main obstacles here:
getElementsByClassName
returns a HTMLCollection<Element>
for older targets and browsers this collection needs to be enumerated with an old-school for
loop. For newer targets (>= ES6) and browsers, see this answer.
- the elements of the collection are of type
Element
but style
is defined on HTMLElement
. Luckily TS automatically narrows a type in the scope of a type guard.