Trying an example given in the DOM lesson but it is not working | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Trying an example given in the DOM lesson but it is not working

I am trying to use the following example given under DOM --> Selecting Elements var elem = document.getElementByID("demo"); elem.innerHTML = "Hello World"; I made a new html document titled 'Practice.html' here is the code: <!DOCTYPE html> <head> <meta charset="utf-8"> <script type="text/javascript" src="jsPractice.js"> </script> </head> <body> <div id="demo">Hello</div> </body> I also made a new javascript file called 'jsPractice.js' here is the content: var elem = document.getElementByID("demo"); elem.innerHTML = "Hello World"; I saved both in the same folder. I am using Brackets program for this and have the live view open in a Chrome window. However all that is displayed is the word 'Hello'. I thought using this javascript code that it would be changed to "Hello World" but it is not. Can anyone help me understand what went wrong?

9th Feb 2017, 8:45 PM
Vampiire
Vampiire - avatar
2 Answers
+ 3
SOLVED: the <script></script> source link must be placed at the BOTTOM of the code. I thought that it was like a CSS link that went in the header. I discovered this by trying putting the manual <script> in different areas of the HTML body (above / below the <div> element). Future reference: <script> link must be the last item in the body of the HTML file (even after </html>). If anyone can comment on why or if this is bad practice I would love to learn more.
9th Feb 2017, 9:06 PM
Vampiire
Vampiire - avatar
0
If I manually type (in the HTML file) <script> var elem = document.getElementByID("demo"); elem.innerHTML = "Hello World"; </script> and refresh the Chrome page then it works. Why will it not work with my external file?
9th Feb 2017, 8:48 PM
Vampiire
Vampiire - avatar