0

I got a uncaught typeError in Sololearn

Hello everyone, I found one error which only be showed in Sololearn code edition, and i dont know the reason because I checked it in other edition(like Notepad) and without error. this is an easy code to change the backgroundColor of element<div> by using JavaScript, like: HTML: <div class="myDiv"></div> <div class="myDiv"></div> <div class="myDiv"></div> CSS: .mySlides { width : 50px; height: 50px; background-color: red; margin: 2px 0; } JS: myFunction() function myFunction(){ var x = document.getElementsByClassName("myDiv"); x[0].style.backgroundColor = "blue"; } please try to code them in Sololearn code edition and you can see the warning below: Uncaught TypeError: Cannot read property 'style' of undefined Line: 5 it is worked if I move "myFunction()" to HTML like add "onload='myFunction()'", but this wont be helped to explain why it has an error in JavaScript part. I am a new guy and I'd like some professional comments. Thanks.

10th Sep 2018, 3:26 PM
chenkowong
chenkowong - avatar
5 ответов
+ 7
GOoooakon Sorry about that. Explanation: When the browser loads, it renders the JavaScript first. That's why we used onload because it will wait for the DOM to load first before the script. Just the same as putting script tag below the body. https://code.sololearn.com/Wlz33Y1JkhdM/?ref=app PS: Mark this as best if you find this helpful.
10th Sep 2018, 4:01 PM
Email Not Activated
+ 4
It is because you call first the myFunction before creating the function itself. try this: function myFunction(){ /*codes*/ } myFunction();
10th Sep 2018, 3:37 PM
Email Not Activated
+ 1
Sleepy Koala thanks for your reply, but pls move the JS code to the JS zone then you can see your code will get an error...
10th Sep 2018, 3:54 PM
chenkowong
chenkowong - avatar
+ 1
Sleepy Koala I got it, thanks!
10th Sep 2018, 4:20 PM
chenkowong
chenkowong - avatar
+ 1
GOoooakon You're welcome. Happy to help. :)
10th Sep 2018, 5:11 PM
Email Not Activated