Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
How can i add row to html table from a list of objects

The object created every time the submit button is clicked , and it pushed to the book_list array but i get messy when i loop in the list to create a row , how can i solve this ? here is the link : https://jsfiddle.net/s7jmkeqL/

let book = new Book(title.value, authName.value, email.value, price.value, date.value, lang.value, radio.value);
book_list.push(book);

// create new rows
function createTd(content) {
  let td = document.createElement('td');
  td.appendChild(document.createTextNode(content));
  tr.appendChild(td);
  table.appendChild(tr);
}

book_list.sort((a, b) => (a.date > b.date) ? 1 : -1); // sort the list by date

for (let i = 0; i < book_list.length; i++) {
  createTd(book_list[i].date);
  createTd(book_list[i].authName);
  createTd(book_list[i].email);
  createTd(book_list[i].title);
  createTd(book_list[i].type);
  createTd(book_list[i].price);
  createTd(book_list[i].lang);
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I believe the problem is, as soon as you create a <td>, you add it to a <tr> but you also immediately append this <tr> to your table. As a result, your table gets filled with <tr> containing only one <td>.

Also I rewrote your for loop so as to avoid repeating yourself, and also make the book keys dynamic, in case you want to add more later (rating, recap, etc. for instance)

let tr;

function createTd(content) {
  let td = document.createElement('td');
  td.appendChild(document.createTextNode(content));
  tr.appendChild(td);
}

const keys = Object.keys(book_list[0]); // ["date","authName",...]

for (let book of books) {
  tr = document.createElement('tr'); // Create a new row for each book

  for(let key of keys) {
    createTd(book[key]); // Append all the cells in the same row
  }

  table.appendChild(tr); // Add the row to the table
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda