0

What would be the optimum strategy to display elements in the js file on the following html page in the div?

html file:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>SO example</title>
  </head>

  <body>

    <div id="text_table"></div>

  </body>

</html>

css file

#text_table {
  top: 10px;
  right: 10px;
  left: 10px;
}

js file

var testResults = [
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
];

var textTable = document.getElementById("text_table");

for (var i = 0; i < testResults.length; i++) {
  /* leaders.innerHTML += */
};

Desired results is:
result

JS fiddle example

techkuz
  • 3,608
  • 5
  • 34
  • 62

1 Answers1

3

You also need to have a inner loop for each array inside the parent array:

var testResults = [
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
];

var textTable = document.getElementById("text_table");
var nHTML = '';
for (var i = 0; i < testResults.length; i++) {
   for(var j=0; j<testResults[i].length; j++){
      nHTML+= testResults[i][j]+ ' ';
   }
   nHTML = '<div>' + nHTML + '</div>';
}
textTable.innerHTML = nHTML;
#text_table {
  top: 10px;
  right: 10px;
  left: 10px;
}
<div id="text_table"></div>

You can also use .replace(/,/g, ' ') without the inner loop like this:

var testResults = [
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
  ['Nickname', 'Points', 'Time', 'Difficulty'],
];

var textTable = document.getElementById("text_table");
var nHTML = '';
for (var i = 0; i < testResults.length; i++) {
   nHTML += '<div>' + testResults[i].toString().replace(/,/g, ' ') + '</div>';
}
textTable.innerHTML = nHTML;
#text_table {
  top: 10px;
  right: 10px;
  left: 10px;
}
<div id="text_table"></div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62