+ 1

My javascript code not working

If i typed like this in javascript Let example = document.getElementById('exampleid'); example.addEventListener('click', () => { }) It shows cant read properties of null addEventListener

11th May 2022, 2:48 AM
Fami-Coder
Fami-Coder - avatar
4 Réponses
+ 3
Fami-Coder JavaScript loads first before loading html contents. In this case 'examleid' will not be available so document.getElementById() will return null So write your code inside this function window.onload = function () { } 2nd one is working because of global object 'document'
11th May 2022, 3:03 AM
A͢J
A͢J - avatar
+ 1
It only works when i typed document.addEventListener('click', () => { })
11th May 2022, 2:51 AM
Fami-Coder
Fami-Coder - avatar
+ 1
It would be nice if you share your real code here But from what i saw I think you are targeting the whole document object not the specified element itself
12th May 2022, 9:21 AM
JSON🌠
0
I also had this problem a long time ago, but it was fixed with a trick I have to remind you that the browser executes the codes from top to bottom, not from bottom to top In SoloLearn, JS codes are executed first, then CSS and then HTML To solve this problem, write the codes after the tag is created You can put JavaScript codes in the script tag Another way is to write codes in window.onload function But it is better if you write the script tag after creating the tag
9th Oct 2022, 1:51 AM
aliz6398suisiTerminatorEmpireBot
aliz6398suisiTerminatorEmpireBot - avatar