Search code examples
javascriptforeachqueryselector

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.


Solution

  • 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.