Eugene Shmorgun Eugene Shmorgun - 1 year ago 76
TypeScript Question

Why does TypeScipt show me error, when I change DOM-element via getElementsByClassName(), but application works anyway?

I have angular2 application. Due to some problems I forced to use inside method of component such code (I understand that it's over than bad, but ...):|

let confirmWindowDOM = document.getElementsByClassName('modal')[0];['z-index'] = "2049";

It produces the error, which I can see in console:

(program):75 ./some/path/to/component.component.ts
(103,28): error TS2339: Property 'style' does not exist on type 'Element'.

But anyway application works as I expected.

So there are some questions:

  1. This code is clear JS. As I understand TypeScript as superset of JavaScript must has no problem with that, however I have error and tests are failed. Even if I change code like this: document.getElementsByClassName('modal')[0].style['z-index'] = "1051";;

  2. How I can suppress this error or fix it ?

Answer Source

getElementsByClassName returns collection of Element. You can use type assertion in order to inform typescript that it is actually HTMLElement:

let confirmWindowDOM = document.getElementsByClassName('modal')[0] as HTMLElement;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download