Home > Mobile >  Angular 12 Object is possibly 'null' in document.getElementById(elementId)
Angular 12 Object is possibly 'null' in document.getElementById(elementId)

Time:10-25

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.

  • Related