+ 1

I'm lost with JavaScript (document.getElementById(".") And clearly making mistakes, Can someone help, I thought I had it but no.

https://sololearn.com/compiler-playground/Wksfx8qN3C1X/?ref=app That's the code there, it's under <script> in HTML

24th Jun 2025, 2:49 PM
Rondell Nagassar
Rondell Nagassar - avatar
8 Answers
+ 4
if you're writing your script inside <script></script> tags in the <body></body> tags, put it at the bottom, under all the body contents, just before the closing </body> tag, so that the html contents is loaded properly first. then your js will be able to search and modify the DOM elements. <body> <!-- your html body contents... --> ... ... <script> // your js </script> </body> </html>
24th Jun 2025, 3:49 PM
Bob_Li
Bob_Li - avatar
+ 3
Rondell Nagassar You're running the script before the HTML is parsed, so your script cannot find the element by the ID. Think of it as searching for a pen from a box holding different kinds of items. If the pen isn't even in the box, how can you find it? Move the script tag along with its code to the end of body(after the HTML code). Or just use external JavaScript(move the js code to the JS tab). If you do that, or still want to keep the script content before the HTML at start of body, make sure to wrap it in an onload event handler: window.onload = () => { // your javascript code }
24th Jun 2025, 3:06 PM
Afnan Irtesum Chowdhury
Afnan Irtesum Chowdhury - avatar
+ 3
Bob_Li, Lisa and Afnan Irtesum Chowdhury. I think I get it now, I'll try it now
24th Jun 2025, 4:25 PM
Rondell Nagassar
Rondell Nagassar - avatar
+ 3
It worked!!!!!!!!! THANK YOU ALL!
24th Jun 2025, 4:28 PM
Rondell Nagassar
Rondell Nagassar - avatar
+ 2
You can only access the html elements with Javascript once the body is fully loaded. Wrap your Javascript with window.onload = () => { ... } To ensure that the code is only executed once the DOM is loaded.
24th Jun 2025, 3:02 PM
Lisa
Lisa - avatar
+ 1
Lisa. I'm sorry I don't understand
24th Jun 2025, 4:21 PM
Rondell Nagassar
Rondell Nagassar - avatar
+ 1
Afnan Irtesum Chowdhury. Or, do you mean that I tried running Java code at the top of the HTML section so it comes like I'm running code without HTML? Like I'm doing things backwards? I'll try it now
24th Jun 2025, 4:24 PM
Rondell Nagassar
Rondell Nagassar - avatar
0
I have a question about my tests in js Concerning the "for loop" Was given 3 tests Test 1# to output "Learning is fun!" With the corresponding code For(k=1; k<=3; k++){ Console.log("Learning is fun!"); } And it was green ticked For the test2 To excute"JS is awesome!" For test3 To execute "some words i have forgotten" But in playground it is outputing Learning is fun JS is awesome That forgotten word Eact 3 times and my test happens to fail.. So if anyone knows how to fix my bug I'm requesting for sm help.. Thank you 😊
25th Jun 2025, 8:24 AM
Bayo Edwin
OSZAR »