Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
show multiple values from the data array in multiple HTML table elements with JavaScript

I want to show multiple values from the data array in multiple HTML table elements at once. And the data value going to change and it needs to be overwritten in HTML. I tried something like below by using nested forEach but it doesn't work. What should I do?

I've tried appendchild but it creates new cells as the data value renewed and I don't want it.

HTML

<table>
  <thead>something</thead>
  <tbody>
    <tr id="changeThis">
      <th>row head</th>
      <td>0</td><!-- 1 -->
      <td>0</td><!-- 2 -->
      <td>0</td><!-- 3 -->
      <td>0</td><!-- 4 -->
    </tr>
  </tbody>
</table>

js

const data = [1, 2, 3, 4]
const changeThis = document.querySelector("#changeThis");

changeThis.forEach(cellItem => {
   data.forEach(dataItem => {
      cellItem.innerHTML = dataItem
   })
})

Thank you for your help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use querySelectorAll to select all tds and add your content

const data = [1, 2, 3, 4]
const changeThis = document.querySelectorAll("#changeThis td");


changeThis.forEach((cellItem,idx) => {
      cellItem.innerHTML = data[idx];
})
<table>
  <thead>something</thead>
  <tbody>
    <tr id="changeThis">
      <th>row head</th>
      <td>0</td><!-- 1 -->
      <td>0</td><!-- 2 -->
      <td>0</td><!-- 3 -->
      <td>0</td><!-- 4 -->
    </tr>
  </tbody>
</table>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can also do that...

const 
  data       = [1, 2, 3, 4]
, changeThis = document.querySelector('#changeThis')
  ;
let index = 0;

for (let cell of [...changeThis.cells])
  {
  if ( cell.matches('td'))
     cell.textContent = data[index++]
  }
<table>
  <thead>something</thead>
  <tbody>
    <tr id="changeThis">
      <th>row head</th>
      <td>0</td><!-- 1 -->
      <td>0</td><!-- 2 -->
      <td>0</td><!-- 3 -->
      <td>0</td><!-- 4 -->
    </tr>
  </tbody>
</table>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda