TypeScript Version: ~2.3.3
Code
let floorElements = document.getElementsByClassName("floor");
for(var i in floorElements) {
floorElements[i].style.height = AppConstants.FLOOR_SIZE_IN_PX + 'px';
}
Expected behavior:
Not display an error.
Actual behavior:
I get this error : Property 'style' does not exist on type 'Element'
You need to cast the Element
to a HTMLElement
, which has got the style property. The reason is that it could also be another type of element that hasn't got the style property.
The simplest way is to cast the return of getElementsByClassName
:
let floorElements = document.getElementsByClassName("floor") as HTMLCollectionOf<HTMLElement>;
Again though, these sorts of general questions should be being asked in Gitter or on StackOverflow.
Ok thanks.
On Jul 4, 2017 8:04 PM, "Kitson Kelly" notifications@github.com wrote:
The simplest way is to cast the return of getElementsByClassName:
let floorElements = document.getElementsByClassName("floor") as HTMLCollectionOf
; Again though, these sorts of general questions should be being asked in
Gitter or on StackOverflow.—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/Microsoft/TypeScript/issues/16920#issuecomment-312920518,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AGaIfzCOu_XfIdyVDdvebVU3WZGfXoD2ks5sKnCrgaJpZM4ONT5A
.
@kitsonk it dosn't work with css style...I getting error "Property 'style' does not exist on type 'HTMLCollectionOf
The function returns a collection of elements, so to access their style you should loop over the elements or index them directly.
@Rep1ay
If you only have one element with that classname, try this:
let drawingBuffer:HTMLElement = document.getElementsByClassName("drawingBuffer")[0] as HTMLElement;
@chadupton It works.Thank you!
Syntactically best way for a single element (below). You don't need to identity the first element within array if it's the only element.
const node = document.querySelector(element) as HTMLElement;
@Rep1ay
If you only have one element with that classname, try this:
let drawingBuffer:HTMLElement = document.getElementsByClassName("drawingBuffer")[0] as HTMLElement;
Thanks it worked!
Most helpful comment
The simplest way is to cast the return of
getElementsByClassName
:Again though, these sorts of general questions should be being asked in Gitter or on StackOverflow.