I am trying to get values from a table and i got this error Uncaught TypeError: Cannot read properties of undefined (reading 'textContent') can someone please help to resolve it?
js
const cards = document.getElementById('cards')
const templateCarrito = document.getElementById('template-carrito').content
const fragment = document.createDocumentFragment()
let carrito = {}
cards.addEventListener('click', e => {
addCarrito(e)
})
const pintarCards = toolList => {
toolList.forEach(producto => {
templateCard.querySelectorAll('td')[0].textContent = producto.tbl_herramienta_ID
templateCard.querySelectorAll('td')[1].textContent = producto.tbl_herramienta_NOMBRE
templateCard.querySelectorAll('td')[2].textContent = producto.tbl_herramienta_DESCRIPCION
templateCard.querySelector('.btn-success').dataset.id = producto.tbl_herramienta_ID
const clone = templateCard.cloneNode(true)
fragment.appendChild(clone)
})
cards.appendChild(fragment)
}
// agregar al arrito
const addCarrito = e => {
if (e.target.classList.contains('btn-success')) {
console.log(e.target.dataset.id)
setCarrito(e.target.parentElement)
}
e.stopPropagation()
}
const setCarrito = objeto => {
const producto = {
id: objeto.querySelector('.btn-success').dataset.id,
nombre: objeto.querySelectorAll('td')[1].textContent,
descripcion: objeto.querySelectorAll('td')[2].textContent,
cantidad: 1
}
console.log(producto)
}
i got an error in nombre: objeto.querySelectorAll('td')[1].textContent, descripcion: objeto.querySelectorAll('td')[2].textContent,
CodePudding user response:
templateCard.querySelectorAll('td')
does not seem to give you as many results as you expect, hence the call to .textContent
fails (one of three elements seem to be null
). You can try to log the results of that selector to see what the resulting elements are.
CodePudding user response:
this is my html
<table class="table table-bordered" width="100%">
<thead>
<tr>
<th scope=" col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Descripción</th>
<th scope="col">Acción</th>
</tr>
</thead>
<tbody id="cards">
</tbody>
</table>
<template id="template-card">
<tr>
<td></td>
<td id="nombre"></td>
<td></td>
<td><button class="btn btn-success"><i
class="fas fa-plus"></i></button></td>
</tr>
</template>