Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById("id") may be null

Tags:

Edit: I'm using TypeScript v2.2.1

I am new to TypeScript and I'm not sure what the cleanest way of dealing with DOM elements that may or may not exist is. Basically, I want to check whether an element exists, and then if it does, add an event listener to it (I have --strict_null_checks turned on).

When I do it the JS-like way:

const myElement = document.getElementById('my-id'); if (myElement) {   myElement.addEventListener('click', (e:Event) => {     // Do stuff.   }); } 

I get the error my_script.ts(3, 3): error TS2531: Object is possibly 'null'.

I can get around this by using a not-null assertion:

const maybeMyElement = document.getElementById('my-id'); if (maybeMyElement) {   const myElement = maybeMyElement!;   myElement.addEventListener('click', (e:Event) => {     // Do stuff.   }); } 

But my understanding is that those sorts of assertions are generally frowned upon, and aesthetically, I don't like creating twice as many variables.

Is there a cleaner way to do this?

like image 424
Evan Hefner Avatar asked Apr 04 '17 22:04

Evan Hefner


People also ask

How do I fix document getElementById null?

This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element. The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.

How can I tell if file getElementById is null?

javascript - Is if(document. getElementById('something')! =null) identical to if(document.

Why document getElementById return null react?

The document. getElementById() method returns null in React when we call the method before the element with the provided ID has been rendered to the DOM or if an element with the ID doesn't exist. To get around this, call the getElementById() method in the useEffect hook. Copied!

Why is an element null?

The input element wasn't loaded yet and the javascript is executed so you get null.


1 Answers

You should type your variables. I haven't done a lot with const, but your second options seems plain wrong (code-smell).

You should be able to get around the warning by strictly typing the variable. The compiler currently sees this as

const myElement: HTMLElement = document.getElementById('my-id'); 

If you change it to also possibly be null, then nulls are allowed:

const myElement: HTMLElement | null = document.getElementById('my-id'); 

Updated

Second option (that I haven't tried): use the ! at the end of the potentially null operation, per https://stackoverflow.com/a/40640854/2084315

const myElement = document.getElementById('my-id')!; 
like image 91
ps2goat Avatar answered Nov 04 '22 23:11

ps2goat