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

210
Visualizações
Using array to store elements doesn't let you change the properties

const divArr = [];
for (let i = 0; i < 5; i++) {
  document.getElementById("h").innerHTML += `<div id=${i}>hello</div>`;
  divArr.push(document.getElementById(`${i}`));
}
console.log(divArr);

let divArrIndex = 0;
setInterval(() => {
  document.getElementById(`${divArrIndex}`).style.backgroundColor = 'green';
  if (divArrIndex > 4) {
    divArrIndex = 0;
  }
  divArrIndex += 1;
}, 1000 / 1);
<div id="h">alsdjf;lkajsdf</div>
The code above successfully turns all the divs green.

But, when I use

divArr[divArrIndex].style.backgroundColor = "green"

instead of

document.getElementById(`${divArrIndex}`).style.backgroundColor='green';

I only get the last div green. Why? codepen: https://codepen.io/sai-nallani/pen/KKopOXZ?editors=1111

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

0

By reassignment to innerHTML, you are destroying and recreating the contents of #h in each iteration of the loop. You create #0, then discard it and create #0 and #1, then discard those and create #0, #1, #2... So the elements you push into the array don't exist any more in your document (though references to them in divArr still keep the garbage collector from destroying them outright).

When you change the colour of divArr[0], you are changing the colour of an element that only exists in memory, but is not in DOM any more. However, #4 is still the original #4, it has not been discarded, since you have performed no further assignments to innerHTML.

One solution is to gather all the divs after you have constructed them all. You can use another loop, but the easiest way would be:

const divArr = Array.from(document.querySelectorAll('#h > div'));

(Depending on what you are doing with it next, you may not need Array.from since NodeList should suffice for many purposes.)

Another solution is to construct elements in their own right, not by changing the parent's innerHTML:

const hEl = document.querySelector('#h');
for (let i = 0; i < 5; i++) {
  const divEl = document.createElement('div');
  divEl.textContent = 'Hello';
  divEl.id = i;
  hEl.appendChild(divEl);
  divArr.push(divEl);
}

This way, every element is created and added to #h without affecting any other elements already there.

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