Skip to content
← Back to Community
innerHTML not displaying text in for loop - JavaScript
Profile icon
ChezCoder
var text = 'Hello World!' var writer = document.getElementById('writer'); for (var i = 0; i < text.length; i++) { //setTimeout(10, function() { writer.innerHTML += text.charAt(i); //}) }
Voters
Profile icon
djallalzoldik
Profile icon
StealthHydra179
Profile icon
ChezCoder
Comments
hotnewtop
Profile icon
AdCharity

Just a suggestion: no need to have event listeners when you can just do document.getElementById("any element with an id").onclick = functionName //no parenthesis afterwards
Also, you must have document.getElementById('writer').innerHTML += text.charAt(i) or else it will not update (it may, but best choice is just to write the full thing out without a variable.)

Profile icon
ChezCoder

@AdCharity writer is the innerHTML

Profile icon
AdCharity

@ChezCoder I ran into this issue earlier. Just try not putting the the thing in a variable because it will not update. Please. It will work. In addition, what is the point of assigning it a variable when you only declare it once?

Profile icon
Vandesm14

You're using the wrong event listener for the button. You want click instead of blur

Profile icon
ChezCoder

@Vandesm14 that was for a test. But the innerHTML still isn't working,

Profile icon
Vandesm14

@ChezCoder You changed it back! You had it right the first time! You have to remove the .innerHTML from the var writer and append it to writer += so it'll then be writer.innerHTML +=

Profile icon
ChezCoder

@Vandesm14 ?? So am I good?

Profile icon
Vandesm14

@ChezCoder No. You need to change the code to what I said: remove the .innerHTML from the var writer and append it to writer += so it'll then be writer.innerHTML +=

Profile icon
ChezCoder
Profile icon
Vandesm14

@ChezCoder Your event listener is set to blur. Set it to click. Other than that, your code should work.

Profile icon
MrEconomical

when you set writer, it is setting writer to the string of the current innerHTML, so writer is just a string and you aren't actually updating the element. To set it, just put another document.getElementById("writer").innerHTML = writer inside the loop

Profile icon
ChezCoder

@MrEconomical yeah i already changed that part. the problem still remains...
here:
https://repl.it/@ChezCoder/Website-sandbox