Why does this return a null? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does this return a null?

https://code.sololearn.com/WIZ8UlsNEsx7/?ref=app Hello, I am trying to console.log the clicker button in the console but the thing is it returns null despite having been put the correct class in the querySelector, any idea ? help appreciated.

23rd Sep 2019, 5:05 PM
Steven Sim
Steven Sim - avatar
3 Answers
+ 1
Sure! So in your function `myFunction` you are using `getElementById` which in theory has the same problem; you can't use it before the page is loaded. But, you will very likely call `myFunction` only after the page is done loading so you never really run into any issues. Like, maybe that function runs when you press a button, which you obviously can't do until the page is ready anyway. I would guess that's why you didn't need it before. The `.querySelector` in your example ran instantly at the very start, and since <script> tags are usually found in the <head> of the page, the <body> wasn't ready yet!
23rd Sep 2019, 5:31 PM
Schindlabua
Schindlabua - avatar
+ 1
You are doing .querySelector before the page is loaded. Wrap your code like so: window.addEventListener("DOMContentLoaded", () => { const clicker = ... ... });
23rd Sep 2019, 5:11 PM
Schindlabua
Schindlabua - avatar
+ 1
Schindlabua Hi, thank you for the answer, it worked, but may I have the explanation why I must use that while some things I made with querySelector didn't use that but still works? or maybe how can I know that the querySelector is done before the page was loaded?
23rd Sep 2019, 5:20 PM
Steven Sim
Steven Sim - avatar