Assignment to the variable document.getElementById (). Innerhtml not working

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);
};

This does not work.

But when I delete .innerhtmlwith the variable MessageElementand set MessageElement.innerHtml= Message, it works.

Why is that? Sorry, I'm new to JavaScript.

+3
source share
4 answers

Since variables and values ​​work in JavaScript. Think of variables as containers. WITH

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

the container MessageElementwill contain a string. Later, with

MessageElement = Message;

you just put the new value in the container, overwriting the previous value / content that the container had. But this does not affect the location at which the previous value occurred.


.innerhtml MessageElement MessageElement.innerHtml = Message, .

DOM

MessageElement.innerHtml = Message

( ), ().

+4

innerHTML , document.getElementById( "happy" ) node.

0

var text=["yuppie", "kkkoseh", "watchdog"];

var messageIndex=0;

function looptext (){
document.getElementById("happy").innerHTML = text[messageIndex];
messageIndex++;
if(messageIndex>=text.length){
    messageIndex=0;
}
}    
window.onload = function() {
setInterval(looptext, 1000);
};
0

@Felix King .

, , W3Schools.
:

  • var MessageElement = document.getElementById( "happy" ) - ( - http://www.microsoft.com/)
  • alert (m) - http://www.microsoft.com/
  • m.innerHTML = "Atul" - Atul .
  • However, the value of m was http://www.microsoft.com/ , as Felix correctly said - "MessageElement. InnerHtml = Message does not assign a new value to a variable.

    <html>
    <head>
    <script>
    function changeLink()
    {
    var m = document.getElementById("myAnchor"); //assigns http://www.microsoft.com/
    alert(m); //
    m.innerHTML = "Atul"
    alert(document.getElementById("myAnchor").innerHTML + " new");
    document.getElementById('myAnchor').innerHTML=m;
    }
    </script>
    </head>
    <body>
    
    <a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
    <input type="button" onclick="changeLink()" value="Change link">
    
    </body>
    </html> 
    

Thanks Felix :)

0
source

All Articles