Home>

There is a table that is generated as follows:

let table= document.createElement ("table");
table.setAttribute ('border', '1');
for (let i= 0; i <
 5; i ++) {
    let newRow= table.insertRow (0);
    for (let j= 0; j <
 5; j ++) {
        let newCell= newRow.insertCell (0);
        newCell.className= "white_cell";
    }
}
document.getElementById ("for_table"). appendChild (table)

There is a button that should change the color of cells from white to black using this function

function change_color () {
    let arrCell_w= document.getElementsByClassName ("white_cell");
    console.log (arrCell_w.length);
    console.log (arrCell_w);
    for (let i= 0; i <
 arrCell_w.length; i ++) {
       //console.log(i)
       //console.log(arrCell_w [i]);
         arrCell_w [i] .className= "black_cell";
    }
}

Judging by the logs, everything that is needed is found, but the color changes only for half of the cells. Can you please tell me what could be the error?

as with .splice, you can simply traverse the collection from the end

Grundy2021-09-24 20:04:41
  • Answer # 1

    getElementsByClassNamereturns liveHTMLCollectiona collection of items.

    In iterationi=== 2there is a call not to the next element of Cell, but to the updated collection, where the second element will nottable.cell, atable.cell.white_cell... The first item is alreadytable.cell.black_celland is not included inarrCell_w... Thus, we refer to the third element, skipping the second. As a result, everything will be painted through one element.

    Let's just turn this collection into an immutable array.

    let table= document.createElement ("table")
    table.setAttribute ('border', '1')
    for (let i= 0; i <
     5; i ++) {
      let newRow= table.insertRow (0)
      for (let j= 0; j <
     5; j ++) {
        let newCell= newRow.insertCell (0)
        newCell.className= "white_cell"
        newCell.textContent= "Cell"
      }
    }
    document.body.appendChild (table)
    function change_color () {
      let arrCell_w= [... document.getElementsByClassName ("white_cell")]
      for (let i= 0; i <
     arrCell_w.length; i ++) {
        arrCell_w [i] .className= "black_cell"
      }
    }
    document.querySelector ("button"). addEventListener ("click", change_color) 
    .white_cell {
      background-color: white;
    }
    .black_cell {
      background-color: darkgray;
    } 
    <
    button start >
    Start <
    /button >