assigning variable to document.getElementById().Innerhtml not working

javascript

Solution

Because that's how variables and values work in JavaScript. Imagine variables to be like containers. With

var MessageElement = document.getElementById("happy").innerHTML

the container `MessageElement` will contain a string. Later on, with

MessageElement = Message;

you simply put a new value in the container, overwriting the previous value/content the container had. But it doesn't have any effect on the location where the previous value was coming from.

But when I remove .innerhtml at variable MessageElement and set the MessageElement.innerHtml= Message , it works.

Now the variable contains a reference to the DOM element and

MessageElement.innerHtml = Message

doesn't assign a new value to the variable (doesn't put a new value in the container), it uses the value of the variable (container).

Problem

See the code below: ``` var text=["yuppie", "kkkoseh", "watchdog"]; var messageIndex=0; function looptext (){ var MessageElement= document.getElementById("happy").innerHTML var Message=text[messageIndex]; MessageElement=Message; messageIndex++; if(messageIndex>=text.length){ messageIndex=0; } } window.onload = function() { setInterval(looptext, 1000); }; ``` It doesn't work. But when I remove `.innerhtml` at variable `MessageElement` and set the `MessageElement.innerHtml= Message` , it works. Why is it so? Sorry, I am a newbie learning JavaScript.

Original source