+ 11

Document.write() removes all HTML content, help!

I'm very new to JS, and I can't figure it out how do I use "innerHTML" command

24th Jun 2019, 2:24 PM
cadbrooke
cadbrooke - avatar
5 Respuestas
+ 8
https://code.sololearn.com/WkAR91MSZ0E9/#html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <div id="Answer"></div> <script> var MyAnswer = document.getElementById("Answer"); var num1 = 1 var num2 = 2 var sum = num1 + num2; MyAnswer.innerHTML = sum; </script> </body> </html> ------- When you use document.write, you're actually overwriting the document itself. You'll want to have an element on your page that'll contain your answer value and then use its innerHTML to display its value. This will prevent you from overwriting the document itself. You can also append the value to any existing element also. Above is a simple example, so learn from it and apply that concept to your own code.
24th Jun 2019, 2:39 PM
AgentSmith
+ 4
And if some content is already there and you need to append something new to it then, element.innerHTML = element.innerHTML + "new content to be added" ; this preserves any existing content.
24th Jun 2019, 8:11 PM
Nidhi
+ 3
is there an exact location where u wanna put the output?
24th Jun 2019, 2:30 PM
gotta feel the vibe
gotta feel the vibe - avatar
+ 2
If you're using innerHTML in the SoloLearn Code Playground through the JS tab, you will need to make sure the element has loaded before attempting to manipulate something that wasn't there at the time you ran your script. A common way to do this is wrapping your function(s) with window.onload. Here's a longer explanation. https://www.sololearn.com/post/111778/?ref=app I hope this helps!
25th Jun 2019, 3:08 PM
Janning⭐
Janning⭐ - avatar
- 3
basically u need to start it all over again
24th Jun 2019, 2:26 PM
Arnizak
Arnizak - avatar