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.
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!
+ 1
You are doing .querySelector before the page is loaded.
Wrap your code like so:
window.addEventListener("DOMContentLoaded", () => {
const clicker = ...
...
});
+ 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?