简体   繁体   中英

Repeatedly add text to div element

Using Javascript, I would like to repeatedly add the same text over and over again to the same div element.

<script>
    while(true) {
        var itstimeto = document.getElementById("duel");   
        var d = "D-";
        itstimeto.innerHTML = itstimeto + d;
        itstimeto = document.getElementById("duel");
    }
</script>
<div id="duel">IT'S TIME TO </div>

However, the div just stays at the text "IT'S TIME TO " with nothing being added onto the text.

My only explanation is that the variable is being repeatedly defined over and over again.

Any help is appreciated!

itstimeto.innerHTML = itstimeto + d;

probably should be

itstimeto.innerHTML = itstimeto.innerHTML + d;

First remove infinite loop. Second use below code

while() {
        var itstimeto = document.getElementById("duel");   
        var d = "D-";
        itstimeto.innerHTML = itstimeto.innerHTML + d;

    }

As @clarmond said in his comments, you want to do itstimeto.innerHTML = itstimeto.innerHTML + d; for getting the inner text and appending further text.

Also I don't see the use of mapping the variable to the same element.

here's the script you need. Just a fair warning that your code might cause you serious trouble when you run it due to the infinite loop you are running

while(true) {
    var itstimeto = document.getElementById("duel");   
    var d = "D-";
    itstimeto.innerHTML = itstimeto.innerHTML + d;
}

1.) Change itstimeto.innerHTML = itstimeto + d to itstimeto.innerHTML = itstimeto.innerHTML + d;

2.) Try change while (true) to setInterval , because while is freeze entire page.

So final code can look like this:

setInterval(function(){ 
var itstimeto = document.getElementById("duel");   
        var d = "D-";
        itstimeto.innerHTML = itstimeto.innerHTML + d;
}, 0);

Remove these lines :

   var d = "D-";
   itstimeto.innerHTML = itstimeto + d;
   itstimeto = document.getElementById("duel");

Change to:

 var d = document.createTextNode('D-');
itstimeto.append(d);

Those are vanilla JS methods, not going to explain. Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript for more detail.

Try using += in order to concatenate your strings. https://plnkr.co/edit/RPUmE7?p=preview

<button onclick="run()">RUN</button>
  <div id="msg">Hello world!</div>    
// Code goes here

    function run() {
      var finalMessage = [] ;
      var msg = document.getElementById("msg").innerHTML;
      for (var i = 0; i < 20; i++) {
          finalMessage.push(msg + " D- <br>");
      }
      document.getElementById("msg").innerHTML = finalMessage.join('');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM