Quiero seleccionar todos los elementos usando querySelectorAll con la variable "amountClass" pero NodeList siempre está vacío
function addingCoin() { const table = document.querySelector('.list__table'); table.addEventListener('submit', (event) => { event.preventDefault(); const walletCryptos = document.querySelector('#usersCrypto'); const coinAmount = event.target.inputAmount; const coinRow = coinAmount.parentElement.parentElement.parentElement; const coinName = coinRow.querySelector('.name').textContent; const coinPrice = coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0]; const coinValue = coinAmount.value*coinRow.querySelector('.price').textContent.match(/\d+(\.\d+)?/)[0]; let amountClass = coinName; let existingCoin = document.querySelectorAll(amountClass); if (existingCoin.length > 0) { existingCoin[0].innerText = coinAmount.value + existingCoin[0].value; } else { const newTr = document.createElement("tr"); const nameTh = document.createElement("th"); const priceTh = document.createElement("th"); const amountTh = document.createElement("th"); const valueTh = document.createElement("th"); nameTh.innerText = coinName; if (coinPrice < 0.95) { priceTh.innerText = parseFloat(coinPrice).toFixed(8); } else { priceTh.innerText = parseFloat(coinPrice).toFixed(2); }; amountTh.innerText = coinAmount.value; amountTh.className += coinName; if (coinValue < 0.95) { valueTh.innerText = parseFloat(coinValue).toFixed(8); } else { valueTh.innerText = parseFloat(coinValue).toFixed(2); }; walletCryptos.appendChild(newTr); walletCryptos.appendChild(nameTh); walletCryptos.appendChild(priceTh); walletCryptos.appendChild(amountTh); walletCryptos.appendChild(valueTh); }}); };Creo que el problema puede estar en esta parte del código:
let existingCoin = document.querySelectorAll(amountClass);¿Qué puedo cambiar para que esto funcione correctamente? ¿Hay alguna otra solución para verificar si existe el elemento con cierta clase?
Necesitas un . al principio para seleccionar una clase.
Recorte el contenido del texto en caso de que tenga espacios en blanco alrededor del texto.
const coinName = coinRow.querySelector('.name').textContent.trim(); let amountClass = '.' + coinNameFinalmente he encontrado la solución:
const amountClass = '.' + coinName; const existingCoin = document.querySelectorAll(amountClass.replace(/ /g,''));