on my html page I load two js scripts at the bottom of the body code:
... html code here ...
<script src="scriptOne.js" type="text/javascript" defer></script>
<script src="scriptTwo.js" type="text/javascript" defer></script>
</body>
</html>
I used defer
to make sure the loading order is kept.
In scriptOne.js I am modifying the DOM by adding a div element to the body with id="findMe"
.
In scriptTwo.js I am trying to get that element because I need to assign an event to it:
const elem = document.querySelector("#findMe");
elem.onclick = (event) => { ... }
This throws an error: elem
is null
.
That makes no sense to me because:
- ScriptTwo.js is getting executed AFTER scriptOne.js. My logs prove that.
- For debugging I put a
console.log(document)
before the querySelector and I can see in the console that the<div id=findMe>
is in the document! Sooo why is the js code not able to get the element?!?!
Does anyone has an idea what causes that behavior? I tried playing around with the defer
and async
script tags, but the results are always the same…
Thank you for helping