SBB SBB - 4 months ago 18
TypeScript Question

Typescript disable all elements within specific ID that has a class

I have a function that is toggling the enabled / disabled statuses of input fields within a div. This div has a unique ID and the div contains inputs that have the same class name.

const el = document.getElementById('slice_' + slice).getElementsByClassName('shiftSlice');
for (let i = 0; i < el.length; i++) {
el[i].disabled = true;
}


When I try this, typescript is telling me that
[ts] Property 'disabled' does not exist on type 'Element'.


Do I need to cast this element in some way to be able to access the disabled property?

Answer Source

You need to tell TypeScript that this is an input element:

const el = document.getElementById('slice_' + slice).getElementsByClassName('shiftSlice');
for (let i = 0; i < el.length; i++) {
    (<HTMLInputElement>el[i]).disabled = true; // note the type assertion on the element
}