why is not list with innerHTML?

0

Because when I put document.write inside for it lists right and in innerHTML it only sends the last position in div ? I wanted to know how I can for print within div from start to end of list, but I'm not getting it.

<head>
  <meta charset=UTF-8/>
  <link rel="stylesheet" type="text/css" href="main.css">
  <script type="text/javascript" src="main.js"></script>
</head>

<body>
  <input type="text" id="text">
  <input type="button" id="click" value="click">
  <input type="button" id="mos" value="mostrar">
  <div id="div"></div>
</body>

<script>
  var lista = [];
  window.onload = function() {
    var text = document.getElementById("text");
    var click = document.getElementById("click");
    var mos = document.getElementById("mos");
    var div = document.getElementById("div");
    click.onclick = function() {
      lista.push(text.value + " <
        br / > "); } mos.onclick=function(){ for (var i = 0; i <
        lista.length; i++) {
        div.innerHTML = lista[i];
      }
    }
  }
</script>
    
asked by anonymous 17.09.2018 / 03:43

1 answer

1

It turns out that multiple calls followed by document.write to write html on the page are all accumulated. See the example:

document.write("um");
document.write(" pequeno");
document.write("<br/><h1>Texto</h1>");

So you can perfectly have a loop that makes document.write multiple times. But with innerHTML does not work that way unless you concatenate the new html with the previous one, using the += operator. Because when you repeatedly do .innerHTML = algo; :

for (var i = 0; i < lista.length; i++) {
    div.innerHTML = lista[i];
    //            ^--
}

You are replacing the previous html with the new html, always with only the last change. Change this line to use += like this:

for (var i = 0; i < lista.length; i++) {
    div.innerHTML += lista[i];
    //            ^--
}

See this change in your working code:

<head>
  <meta charset=UTF-8/>
  <link rel="stylesheet" type="text/css" href="main.css">
  <script type="text/javascript" src="main.js"></script>
</head>

<body>
  <input type="text" id="text">
  <input type="button" id="click" value="Inserir texto">
  <input type="button" id="mos" value="Mostrar">
  <div id="div"></div>
</body>

<script>
  var lista = [];
  window.onload = function() {
    var text = document.getElementById("text");
    var click = document.getElementById("click");
    var mos = document.getElementById("mos");
    var div = document.getElementById("div");
    click.onclick = function() {
      lista.push(text.value + " <br / > ");
      text.value = "";
    }
    mos.onclick = function() {
      for (var i = 0; i < lista.length; i++) {
        div.innerHTML += lista[i];
      }
    }
  }
</script>
    
17.09.2018 / 11:56