In Angular 12 I keep getting this issue:
I want to have an show an element by id ...so I have this:
document.getElementById(elementId).style.visibility = 'hidden';
I keep getting:
Object is possibly 'null'.
I don't know what it's talking about :(
How can I stop this error?
CodePudding user response:
Check if the returned value from getElementById
isn't null:
const element = document.getElementById(elementId);
if (element) {
element.style.visibility = 'hidden';
}
The return type of getElementById
is HTMLElement | null
, as it's very possible the function couldn't find the element.
You might know for sure the element exists, but your code doesn't.