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

260
Vistas
Agregue una matriz de objetos como elementos a la tabla existente td

Tengo una mesa existente. Tengo las celdas td mostradas como bloques intencionalmente. :) Mi objetivo es agregar etiquetas dentro de cada uno de los td creando intervalos con una clase específica y luego agregarlos a la celda de la tabla. Estoy usando una matriz de objetos con los datos de la etiqueta, un 'icono' y un 'nombre'.

La meta

Tengo problemas para aplicar los íconos individualmente a los td . Todos se agrupan en cada celda.

ingrese la descripción de la imagen aquí

Algunos problemas que estoy tratando de resolver:

  1. Agregue cada objeto (un icono y una etiqueta) a cada celda
  2. Al crear los elementos, agregue una clase de icono al intervalo de iconos y una clase de etiqueta al intervalo de etiquetas.
  3. Aplíquelos apropiadamente en el orden que se muestra en el objeto

Probé un montón de cosas diferentes (ver comentarios de código) y muchas buenas publicaciones aquí en SO, pero esta función parece acercarme más a mi objetivo. Cualquier ayuda es muy apreciada.

 let items = [{ id: "🐌", name: "snail" }, { id: "🐜", name: "ant" }, { id: "🪲", name: "beetle" }, { id: "🐝", name: "honeybee" }, { id: "🕷", name: "spider" } ]; function createLabel(obj) { // let loc = document.getElementsByTagName("#profiles td"); let loc = document.querySelectorAll("#profiles td"); if (typeof obj !== "undefined" && obj !== null) { // loop through td's for (let i = 0; i < loc.length; i++) { // apply object data obj.forEach((item) => { Object.values(item).forEach((text) => { // loc.prepend(span); // I also tried my for loop here with similar weird results let span = document.createElement("span"); let textNode = document.createTextNode(text); // 'id' should get .icon // 'name' should get .label span.className = 'icon'; span.append(textNode); loc[i].prepend(span); }); }); } } } createLabel(items);
 <table id="profiles"> <tr> <td>Snail Stuff</td> <td>Ant Stuff</td> <td>Beetle Stuff</td> <td>Honeybee Stuff</td> <td>Spider Stuff</td> </tr> </table>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Estabas usando document.querySelectorAll . Simplemente puede usar document.querySelector para obtener la tabla y ejecutar un bucle for of para agregar el elemento a la tabla

 let items = [ { id: "🐌", name: "snail", text: "Snail Stuff" }, { id: "🐜", name: "ant", text: "Ant Stuff" }, { id: "🪲", name: "beetle", text: "Beetle Stuff" }, { id: "🐝", name: "honeybee", text: "Honeybee Stuff" }, { id: "🕷", name: "spider", text: "Spider Stuff" } ]; function createLabel(obj) { const loc = document.querySelector("#profileRow"); const elements = []; for (const item of obj) { const el = document.createElement("td"); el.innerHTML = `<span class='icon'>${item.id}</span> <span class='label'>${item.name}</span> ${item.text}`; elements.push(el); } loc.append(...elements); } createLabel(items);
 td { display: block; border: 1px solid #ccc; } span { display: inline-block; } .icon { background: yellow; width: 3rem; text-align: center; } .label { font-weight: bold; width: 6rem; } .pie { margin-top: 4rem; }
 <!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <table id="profiles"> <tr id="profileRow"></tr> </table> </body> </html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Creo que el problema es que estás recorriendo dos veces los elementos. Con lo primero debería ser suficiente

Esta es mi oportunidad:

 let items = [{ id: "🐌", name: "snail" }, { id: "🐜", name: "ant" }, { id: "🪲", name: "beetle" }, { id: "🐝", name: "honeybee" }, { id: "🕷", name: "spider" }, ]; //created a function so that we don't repeat the span creation function createSpan(text, className) { let span = document.createElement('span') span.className = className; let textNode = document.createTextNode(text) span.append(textNode) return span } function createLabel(obj) { // let loc = document.getElementsByTagName("td"); let loc = document.querySelectorAll("#profiles td"); if (typeof obj !== "undefined" && obj !== null) { // loop through td's for (let i = 0; i < loc.length; i++) { // apply object data // loc.prependspan; //destructure the item so that we get its properties, it's the same as doing const id = items[i].id and const name=items[i].name but all in one line! const { id, name } = items[i] const iconSpan = createSpan(id, 'icon') // 'id' should get .icon // 'name' should get .label let labelSpan = createSpan(name, 'label') loc[i].prepend(iconSpan, labelSpan); // loc[i].insertAdjacentHTML('afterbegin', span); ; } } } createLabel(items);
 <table id="profiles"> <tr> <td>Snail Stuff</td> <td>Ant Stuff</td> <td>Beetle Stuff</td> <td>Honeybee Stuff</td> <td>Spider Stuff</td> </tr> </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