Why doesn’t it list with innerHTML?

Asked

Viewed 88 times

0

'Cause when I put document.write within the for The list of innerHTML he only sends the last position in the div? I was wondering how do I do for the for print within the div from the beginning to the end of the list, but I’m not getting.

<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>

1 answer

1

Turns out several calls in a row to 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 might as well have one loop what makes document.write several times. But with innerHTML does not work like this unless you concatenate the new html with the previous one using the operator +=. 'Cause when you do it over and over .innerHTML = algo; :

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

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

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

See this change in your code working:

<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>

  • Thank you very much helped me a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.