0

Is the button element special or does the code work differently in the Sololearn Playground?

What is happenong?? When I create a button with the I'd "one" the following: var x = document.getElementsByTagName("button"); x[0].innerHTML = "Goodbye"; yield the error "Cannot set innerHTML as undefined "

18th Nov 2018, 10:12 PM
Stan Berger
Stan Berger - avatar
4 Answers
+ 2
Odds are you are attempting to set x before the DOM is loaded. Any access to DOM elements must wait for the page to be loaded. SoloLearn starts the JavaScript faster that some web browsers do so you might get away without checking. However, that is a bad programming practice. To solve this, make a function that is run on the onload event. You can call it in your body tag: <body onload="initialize();"> Or in JavaScript: window.onload = function() { // code }
19th Nov 2018, 2:49 AM
John Wells
John Wells - avatar
+ 2
Yes, thank you!! This is such a wonderful community of programmers!!
19th Nov 2018, 3:24 AM
Stan Berger
Stan Berger - avatar
+ 2
I like putting it in the body tag - that worked perfectly! Thanks again!
19th Nov 2018, 3:29 AM
Stan Berger
Stan Berger - avatar
0
In Sololearn, using x =0 OR x=1 changes both to "new text" but x=2 OR x=3 changes the second paragraph only to "new text". Is this another onload or some other issue? function setText() { var a = document.getElementById("demo"); var arr = a.childNodes; for(var x=0;x<arr.length;x++) { arr[x].innerHTML = "new text"; } } //calling the function with setTimeout to make sure the HTML is loaded setTimeout(setText, 500);
1st Dec 2018, 3:54 AM
Stan Berger
Stan Berger - avatar