Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Console blocking execution because getElementbyId is null (but I want it to be)

EDIT: The answers of Mr. Veron, Mr. Spungin, and Mr. Shah fit my needs perfectly. My error is apparent, and the console’s warning perfectly sensible. Thank you all.

I’m trying to determine the existence of an element in the DOM. In accordance with what extant posts have suggested, I’ve resorted to using getElementbyId + querySelector and then checking if it’s null/undefined with a conditional.

let target = document.getElementbyId(a).querySelector(b)

if(typeof(target) != 'undefined' && target != null){
...
}

Here’s where I run into an error. When the first line executes, my console tosses up the error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Uncaught (in promise) TypeError: document.getElementById(...) is null

because "target" is null — but I intend for it to be null, and thus am mildly irked that the console is for once acting against my interest.

This is an implementation offered and endorsed by many on Stack Overflow — and yet I cannot easily find people facing the same obstruction that I am. Therefore, I’d appreciate any explanations for why such a warning is needed or ways to circumvent it (a better implementation than what has been widely suggested ). Much thanks.

>Solution :

check for undefined before calling querySelector

let target = document.getElementbyId(a) ? document.getElementbyId(a).querySelector(b) : undefined
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading