Entonces tengo la tabla:
<table class="checkout-list"> <thead> <tr> <th class="checkout-title">item</th> <th class="checkout-title">amount</th> <th class="checkout-title">total</th> </tr> </thead> <tbody> <tr> <td class="checkout-info"></td> <td class="checkout-info"></td> <td class="checkout-info"></td> </tr> <tr> <td class="checkout-info"></td> <td class="checkout-info"></td> <td class="checkout-info"></td> </tr> </tbody> </table> Y con javascript quiero tomar valores de thead tr th y establecerlos en tbody tr td como atributos. Intenté esto:
let title = []; document.querySelectorAll('.checkout-title').forEach(el => { title.push(el.innerHTML); }); document.querySelectorAll('.checkout-info').forEach((el, index) => { el.setAttribute('data-title', title[index]); }); Bus tal como está ahora, solo logro asignar valores al primer tbody tr td child y el segundo a la izquierda con undefined se ve así:
<tbody> <tr> <td class="checkout-info" data-title="item"></td> <td class="checkout-info" data-title="amount"></td> <td class="checkout-info" data-title="total"></td> </tr> <tr> <td class="checkout-info" data-title="undefined"></td> <td class="checkout-info" data-title="undefined"></td> <td class="checkout-info" data-title="undefined"></td> </tr> </tbody>¿Cómo debo arreglar esta asignación indefinida?
El problema con el código es que solo hay tres nodos con querySelector document.querySelectorAll('.checkout-title') y seis nodos con querySelector document.querySelectorAll('.checkout-info') . Es por eso que hay valor para los primeros 3 nodos e undefined para los últimos tres nodos.
Debe acceder a los nodos desde la matriz de title con title[index % header.length] para que recorra el título dos veces y asigne el atributo correctamente
let title = []; const header = document.querySelectorAll('.checkout-title'); header.forEach(el => { title.push(el.innerHTML); }); const nodes = document.querySelectorAll('.checkout-info'); nodes.forEach((el, index) => { el.setAttribute('data-title', title[index % header.length]); }); <table class="checkout-list"> <thead> <tr> <th class="checkout-title">item</th> <th class="checkout-title">amount</th> <th class="checkout-title">total</th> </tr> </thead> <tbody> <tr> <td class="checkout-info"></td> <td class="checkout-info"></td> <td class="checkout-info"></td> </tr> <tr class="delivery_price"> <td class="checkout-info"></td> <td class="checkout-info"></td> <td class="checkout-info"></td> </tr> </tbody> </table>