Home > Software engineering >  How to display data from json into HTML using js table
How to display data from json into HTML using js table

Time:05-24

How can I insert this code into js table

if (data.players.length) {data.players.forEach((ply)=>{
            
            let plycont = document.createElement('div')
            
            
            let plyspan = generate_colored_span(ply.name)
            plyspan.className = 'tracker_plyname'
            plycont.appendChild(plyspan)
            
            plycont.appendChild(wrap_span(ply.score, 'tracker_plyscore'))
            
            plycont.appendChild(wrap_span(ply.ping == '0' ? 'BOT' : ply.ping, 'tracker_plyping'))
            tracker_playerslist.appendChild(plycont)
        })} 

JSON api data I want to use: "players":[ { "name":"", "score":"", "ping":"" }]

HTML output:

<table >
  <thead>
    <tr>
      <th>Players</th>
      <th>Score</th>
      <th>Ping</th>
    
    </tr>
  </thead>
  <tbody></tbody>
  </table>

CodePudding user response:

You can create create table and

const addRow = (el, data) => {
  if (data.length) {
    data.forEach((ply) => {
      const row = document.createElement("tr");
      row.innerHTML = `
        <td>${ply.name}</td>
        <td>${ply.score}</td>
        <td>${ply.ping}</td>
      `;
      el.appendChild(row);
    });
  }
};

const table = document.querySelector("tbody");
const data = [
  {
    name: "Player 1",
    score: "100",
    ping: "100",
  },{
    name: "Player 2",
    score: "200",
    ping: "200",
  }
];
addRow(table, data);
td {
 padding: 4px 24px;
}
<table >
  <thead>
    <tr>
      <th>Players</th>
      <th>Score</th>
      <th>Ping</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

  • Related