0

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
7 Réponses
+ 3
if you're putting your script inside <script></script> tags inside the <body></body> tags, put it at the bottom, just before the closing </body> tag, so that the html is loaded properly. <body> your html... ... ... <script> your js </script> </body> </html>
24th Jun 2025, 3:49 PM
Bob_Li
Bob_Li - avatar
+ 2
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
+ 2
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
+ 2
It worked!!!!!!!!! THANK YOU ALL!
24th Jun 2025, 4:28 PM
Rondell Nagassar
Rondell Nagassar - avatar
+ 1
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
0
Lisa. I'm sorry I don't understand
24th Jun 2025, 4:21 PM
Rondell Nagassar
Rondell Nagassar - avatar
0
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