An issue arises in typescript due to the return type of document.getElementById
being HTMLElement | null
. While you can disable this check by adjusting strictNullChecks: false
in your tsconfig, it is a beneficial validation as the call could potentially yield null if the DOM element does not exist. There are alternative ways to handle this situation without turning off the check.
One approach is to verify for null
and manage the scenario:
const element = document.getElementById('div0');
if (element === null) {
// Implement appropriate handling for this case
throw new Error('Element "div0" does not exist.');
}
// Following the initial check, the error will no longer be thrown
element.parentNode.removeChild(element);
Another method is utilizing the !
operator to signify to typescript that the value should never be null:
const element = document.getElementById('div0')!;
element.parentNode.removeChild(element);
It's important to note that this technique may trigger a runtime error if element
is null during execution.
Alternatively, you can employ the ?
to invoke removeChild
only when the element is not null
:
const element = document.getElementById('div0');
element?.parentNode.removeChild(element);
This strategy will solely access parentNode
on element
if it is not null. If it evaluates to null, the expression becomes null and removeChild
is not executed.