Why this JavaScript code isn't working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why this JavaScript code isn't working?

var test = document.getElementById('test'); test.innerHTML = 'hello'

14th Nov 2023, 8:20 PM
JonySVK
JonySVK - avatar
3 Answers
+ 7
This is because the javascript is triggered faster than the html document has time to load. Use the "onload" method for example like this: onload = ()=>{ var test = document.getElementById('test'); test.innerHTML = 'hello'; }
15th Nov 2023, 2:21 AM
Solo
Solo - avatar
+ 5
Solo Thank you very much! Your solution works.
15th Nov 2023, 6:49 AM
JonySVK
JonySVK - avatar
+ 4
what dom element are you applying it to? it works for div, p, h1,h2 etc. it will not work for img. also, try to avoid innerHTML unless you absolutely have to. use textContent instead https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
14th Nov 2023, 9:54 PM
Bob_Li
Bob_Li - avatar