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?
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With