Search code examples
javascripthtmlinnerhtml

How to make div act as console?


Wanted to ask how to make a div act as a console. For example code:

  buyBank: function(){
          if(this.cash>(1+this.banks)*10){
            this.cash -= (1+this.banks)*10;
            this.banks++;
            amount3.innerHTML = this.banks;
            price3.innerHTML = "$"+(1+this.banks)*10;
            logger.innerHTML = "Bank nupirktas!";
        }else{
            console.log("Nepakanka pinigu bankui!");
        }
    }

buy3btn.addEventListener("click", function(){
    game.buyBank();
});

What id does now, if statement = true, it writes "Bank nupirktas" to a div (logger). However, on second click nothing changes (probably posts to the same line). I want it to break line and post a new one on every click (while keeping the old ones).


Solution

  • That's because you're overwriting the previous content.

    var div = document.querySelector('div');
    div.innerHTML = 'You will never see me';
    div.innerHTML = 'Because I overwrite it';
    <div></div>

    Instead, you need to append content to it.

    function log(msg) {
      var div = document.querySelector('div');
      div.innerHTML += msg + '<br />'; // Add a line break
    }
    
    log('First line.');
    log('Second line.');
    log('Third line.');
    <div></div>