Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda