0

How come this throws ans error?

I'm trying to learn JS but so far the language makes no sense to me... It's like it's just random when it works or not. However, how come this line works in the tutorials, but not in Playground? var x = document.getElementsByClassName("example"); x[0].innerHTML = "Hello World!"; The whole thing: https://code.sololearn.com/WalX6coidtMX/?ref=app

5th Feb 2020, 10:23 PM
Mike Mortensen
Mike Mortensen - avatar
9 odpowiedzi
+ 1
Don't put tags in it, as it's Javascript: window.onload = function() { var x = document. getElementByClassName("example"); x[0].innerHTML = "Hello World!"; }
5th Feb 2020, 10:40 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
It's returning a error because Sololearn runs the HTML code after the Javascript code, meaning Javascript doesn't have access to the div with the class. In order to fix this, simply encase your Javascript code with window.onload() = function() {//your code goes here}, which runs the code inside it once the HTML code, also know as the window(the visible part), loads.
5th Feb 2020, 10:28 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
I figured it out "window.onload" and not "window.onload ()"
5th Feb 2020, 10:39 PM
Mike Mortensen
Mike Mortensen - avatar
+ 1
Confusing 🤣 Well it works now. I can see that my 8 years with C and C# does not help me much in JS. Everything is 'var' so it's impossible to know what type I'm working with. It's like a whole new world 🤷‍♀️😅
5th Feb 2020, 10:42 PM
Mike Mortensen
Mike Mortensen - avatar
+ 1
Yup, definitely. C# is very specific about types(string, int, bool, etc., even whether it's public or private) compared to Javascript. But Javascript is much better for web development than C# is, as web development is it's main purpose.
5th Feb 2020, 10:45 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
Which is why I decided to learn it. I want to have a Better understanding of webpages as I previously have only worked a small amount with HTML and CSS.
5th Feb 2020, 10:47 PM
Mike Mortensen
Mike Mortensen - avatar
0
So that's why there's no script tags in there either?
5th Feb 2020, 10:32 PM
Mike Mortensen
Mike Mortensen - avatar
0
You can put <script></script> tags in the HTML, and then you wouldn't need the window.onload() function as the script is running in the window.
5th Feb 2020, 10:34 PM
Jianmin Chen
Jianmin Chen - avatar
0
I says window.onload () is not a function? Should I just put emptt tags in? Or what am I doing wrong?
5th Feb 2020, 10:38 PM
Mike Mortensen
Mike Mortensen - avatar