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

131
Visualizações
Re: How to target child nodes in HTML collection

I am new to programming and this is my first question. The problem I am having is I am trying to use DOM manipulation on all the child nodes of an html collection. I am expecting the nodes to change background color when they are hovered. Here is what I have tried so far:


        let x = 0;

do{
    const square = document.createElement("div");
square.className = "squares";
square.setAttribute("id","block");
    document.getElementById("container").appendChild(square);
    x++;
}
while(x < 16);

var container = document.getElementById("container");
var cells = container.childNodes;

cells.forEach(function(){
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}
});
console.log(`${cells.length}`);

This doesn't work even though console.log shows 16 child nodes being targeted.

var container = document.getElementById("container");
var cells = container.children[0];
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}

I have tried this and can use index but of course only that cell will change bg color. I want any cell that is hovered to change also.

I am at a loss for what I am doing wrong here. If anyone can point me in the right direction I would greatly appreciate it.

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

0

Welcome to Stack Overflow. There is an issue in your forEach cycle. Consider the following:

cells.forEach(cell => {
  cell.onmouseover = () => {
    cell.style.backgroundColor = "black"
  }
})

Note that you need to refer to cycle variable instead of the cells array.

about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of attaching listeners to all the squares you can use event delegation and just have one listener on the container that captures the events from its children as they "bubble up" the DOM.

// Cache the container element, and add a listener to it
const container = document.querySelector('.container');
container.addEventListener('mouseover', handleMouse);

// Create some squares HTML by pushing template
// strings into an array
const html = [];

for (let i = 1; i < 10; i++) {
  html.push(`<div class="square">${i}</div>`);
}

// Add that HTML to the container making sure
// we join the array of strings into one string
container.innerHTML = html.join('');

// When a event is fired check that it was
// was from an element with a square class
// and then add an active class to it
function handleMouse(e) {
  if (e.target.matches('.square')) {
    e.target.classList.add('active');
  }
}
.container { display: grid; grid-template-columns: repeat(3, 50px); grid-gap: 0.2em; }
.square { font-size: 1.2em; padding: 0.7em 0.2em; background-color: #565656; color: white; text-align: center; }
.square.active { background-color: thistle; color: black; cursor: pointer; }
<div class="container"></div>

Additional documentation

  • Template/string literals
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