+ 3
"<div class="img"></div> " won't show when scrolling. I have this error: Cannot read property 'classList' of null
Here's the link to my code: https://code.sololearn.com/Ww0BdBlh8WeJ
8 Réponses
+ 6
One way of curing is:
Change your line 45 from
img.classList = '';
to
img.classList = 'img';
Otherwise the querySelector will return null once you scrolled a little bit because there does not exist the DOM with class img anymore.
https://code.sololearn.com/Wo0evwRYEwr8/?ref=app
+ 4
Second way of curing is:
1. Declaring the DOM variable in global context
2. Moving your querySelector to a function added to load listener of window.
Demo:
https://code.sololearn.com/W69wf6gKIe90/?ref=app
In this way, it is ensure that the getElement will be carried out once at the beginning only, when the DOM with class name img is still there.
Note that : the image will not be shown again with this method. Because your image is attached to the img class.
+ 3
Thanks, Kougaiji.
For the second way, although you have not used, it involves the concept of closure.
When you have time, here is David Carroll's pick of 3 readings from beginner to advanced:
https://www.sololearn.com/post/45261/?ref=app
+ 2
Thank you very much for solving this Gordon! A very simple solution yet so hard for me to find out lol. Thanks again!
+ 2
You are welcome, Kougaji.
And right, you inspire me, I should also teach you how to find out the problems.
We add console.log in between the lines to help us understand the values of variables in intermediate states.
https://code.sololearn.com/WuBzocc861ZK/?ref=app
Adding console.log in your original version, we can see that actually the DOM is got successfully in its first attempt.
P. S. I think this is very useful for most SoloLearners. If you don't mind, I'll use this copied code of yours as a demo of how to apply console log in debugging for later Q&A questions. Can I?
+ 2
Sure go ahead! It would of great help to fellow SoloLearners. Thanks a lot!
+ 2
That's strange, I just tried again, and all the links work
+ 1
I'd like to read them but the link is not working...