Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use document.getElementById() method in TypeScript?

I am trying to reset HTML Form in order to clear all the values in the input fields using;

document.getElementById('myForm').reset(); 

But I can use that in typescript, it's giving me an error saying document.getElementById('myForm') may be null

How can I solve this issue?

like image 726
Madhu Avatar asked Sep 25 '18 06:09

Madhu


People also ask

What is the getElementById () function?

The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.

What is document getElementById () value?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

Can you use getElementById in angular?

The getElementById method returns the element with the ID Attribute with the specified value. This method is most common in HTML DOM and is used almost every time we manipulate, get info from, or element in our document.


1 Answers

Typescript will force you to check the value is not null if you use the strictNullChecks option (or strict which includes strictNullChecks). You can either perform the test or use a not null assertion (!). Also you will need to use a type assertion to assert the html element is an HTMLFormElement as by default it will be just an HtmlElement and reset is present only HTMLFormElement

Just an assertion Assertion:

(document.getElementById('myForm') as HTMLFormElement).reset();

Assertion with check (recommended):

let form = document.getElementById('myForm')
if(form) (form as HTMLFormElement).reset(); 

Not null assertion (if you want to access just HtmlElement member):

document.getElementById('myForm')!.click()
like image 75
Titian Cernicova-Dragomir Avatar answered Sep 22 '22 13:09

Titian Cernicova-Dragomir