For loop with array not working

I have a div with ID="ranking", and I would like to put there some information about a JavaScript array with a table in which each row has buffer columns: one for dados[i][25]and another for dados[i][26].

My code is:

function dadosRanking(dados){
        document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
        for(var i=1;i<6;i++)
        {
          document.getElementById("ranking").innerHTML += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
        }
        document.getElementById("ranking").innerHTML += '</table>';
}

The code I expect is the following:

<table class="table">
  <tr>
    <td valign="middle" class="question" colspan=2>
      <h1>RANKING (+ PONTOS)</h1>
    </td>
  </tr>
  <tr>
    <td>PONTOS</td>
    <td>UTILIZADOR</td>
  </tr>
  <tr>
    <td>
      100
    </td>
    <td>
      Username
    </td>
  </tr>
</table>

However, the HTML script code is as follows:

<table class="table">
  <tr>
    <td valign="middle" class="question" colspan=2>
      <h1>RANKING (+ PONTOS)</h1>
    </td>
  </tr>
  <tr>
    <td>PONTOS</td>
    <td>UTILIZADOR</td>
  </tr>
</table>
"100Username"
+4
source share
1 answer

Each time you update innerHTML, the browser will parse it and display to do this, it will also try to “fix” your HTML. This may have unintended consequences. Instead of clicking on innerHTMLwith the definition of a partial table, assemble the HTML in a separate value and click once innerHTML.

function dadosRanking(dados){
    var s = "";
    s += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'
    for(var i=1;i<6;i++) {
        s += '<tr><td>' + dados[i][25] + '</td><td>' + dados[i][26] + '</td></tr>';
    }
    s += '</table>';
    document.getElementById("ranking").innerHTML += s;
}

document.getElementById("ranking").innerHTML += '<table class="table"><tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr><tr><td>PONTOS</td><td>UTILIZADOR</td></tr>'

innerHTML :

<table class="table">
  <tr><td valign="middle" class="question" colspan=2><h1>RANKING (+ PONTOS)</h1></td></tr>
  <tr><td>PONTOS</td><td>UTILIZADOR</td></tr>
</table>

, !

document.getElementById("ranking").innerHTML += '<tr><td>foo</td><td>bar</td></tr>';

innerHTML

<table>..</table>
foobar

<tr> <td> , .

document.getElementById("ranking").innerHTML += '</table>';

innerHTML , </table> , .

+7

Source: https://habr.com/ru/post/1619565/


All Articles