+ 2
How do I change the image src attribute through javascript?
My code works in the Sololearn app but when I try to run it in Safari, I get the error: TypeError: null is not an object (evaluating ‘document.getElementById("image").src = "https://static.turbosquid.com/Preview/2014/07/11__21_03_51/Blue03.jpg4006e534-fd54-4b54-afc9-8c614f82501bOriginal.jpg"') Line: 28 I want to change the image depending on what animal the player gets, so I tried to change the src attribute through javascript. Any possible solutions to this error? Code: https://code.sololearn.com/WjN7Ojf1Sigr/?ref=app
8 Respuestas
+ 6
Add your js script inside this function
window.onload=function(){
all your js code goes here
}
so basically why you are getting error at line 22 is because js is getting loaded before html document and so accessing getElementbyId(image element doesn't exist yet) returns null ,so window.onload prevents it by running js script only after html document is loaded ,
You said it's working fine on sololearn but it wasn't working for me ,maybe try applying the solution above
+ 3
Tori the crafter
Some extra context based on your first sentence.
https://code.sololearn.com/WcdoF4PGPyDC/?ref=app
+ 3
tori the crafter
Yes, to be safe when using Sololearn playground/{}, you can use events such as window.onload or DOMContentLoaded.
Another option is to place your js code at the bottom of the HTML body using the script tags.
If you take a look at some web codes from other community members you will see all three options are used at one time or another.
+ 2
I am running web codes on sololearn only ,so it always works for me
+ 1
Emanuel Maliaño Thanks for the information, but I’m wondering why I’m getting this error specifically. If you could explain that would be great
+ 1
I think your solution worked! Let me know if it works for you too! Abhay
+ 1
Thanks for the explanation! That clears a lot of things up. In the future, should I just add window.onload to be safe? ODLNT