Can't get value of HTMLElement

Viewed 147

I'm currently using Ionic React with .tsx files. When I do a simple document.getElementById("input-id").value, got the error Property 'value' does not exist on type 'HTMLElement'. Looking for a way to solve this, fount the typescript parser <HTMLInputElement>, but doesn't work because HTMLElement doesn't have many HTMLInputElement props.

How can I get the value of an input in this context?

My code is here. It can't even compile because of Typescript erros:

handleChange() {
  const input = document.getElementById("id").value;
}

render() {
  return (
    <IonPage>
      <IonContent fullscreen>
        <TextField
          id="id"
          label="Input"
          variant="outlined"
          required
        />
      </IonContent>
    </IonPage>
  );
}
1 Answers

You can use casting with the as keyword and declare a variable that you know to be of HTMLInputElement type. Then access its value property.

const inputElement: HTMLInputElement = document.getElementById("input-id") as HTMLInputElement;
console.log(inputElement.value)
Related