Как правильно закрасить клетки шахматной доски на Vanilla JS

const chessWrap = document.createElement('div')
chessWrap.style.height = '160px'
chessWrap.style.width = '160px'
document.body.appendChild(chessWrap)

for (let i = 0; i < 8; i++) {
    const item1 = document.createElement('div')
    item1.style.height = '20px'
    item1.style.width = '20px'
    item1.style.background = '#000'
    item1.style.float = 'left'
    chessWrap.appendChild(item1)
    for (let j = 0; j < 8; j++) {
        const item2 = document.createElement('div')
        item2.style.height = '20px'
        item2.style.width = '20px'
        item2.style.background = 'red'
        item2.style.float = 'left'
        chessWrap.appendChild(item2)
    }
}
console.log(chessWrap)

Ответы (2 шт):

Автор решения: HTO HOT

Если вы делаете какую-нибудь игру , лучше конечно это делать через canvas. Но возможно у вас какое-то другое применение этому, я смог сделать это и таким способом.

function createChess(scaleSquare,scaleCell){////scaleSquare размер поля (10х10) scaleCell размер клетки в пикселях(20px x 20px)
  const chessWrap = document.createElement('div');
    chessWrap.style.height = scaleSquare * scaleCell + 'px';///// узнаём новую высоту поля
    chessWrap.style.width = scaleSquare * scaleCell + 'px';///// узнаём новую ширину поля
    chessWrap.style.display = 'flex';/// Добавил флексы
    chessWrap.style.flexWrap = 'wrap';
    document.body.appendChild(chessWrap);
    

    for (let i = 0; i < scaleSquare; i++) { 
      for (let j = 0; j < scaleSquare; j++) {  ////// идёт перебор всего поля (10 x 10)
        const item = document.createElement('div');
        item.style.height = scaleCell +'px';
        item.style.width = scaleCell +'px'; //// подставляем размеры из переменной scaleCell
        if((i+j)%2===0 ){ //Формула отвечающая за чередование
          item.style.background = '#000';
        }else{
          item.style.background = 'red'
        }
         chessWrap.appendChild(item);
          
      }
  }
}
createChess(10,20)
createChess(10,10)
createChess(8,30)

→ Ссылка
Автор решения: Виталик Сычев
function renderChess(n, w = 20) {
        const chessWrap = document.createElement('div');
        chessWrap.style.display = 'flex'; /// Добавил флексы
        chessWrap.style.flexWrap = 'wrap';
        document.body.appendChild(chessWrap);

        const size = n * w;
        chessWrap.style.width = `${size}px`;

        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++) {
                const item = document.createElement('div');
                item.style.height = `${w}px`;
                item.style.width = `${w}px`;
                if ((i + j) % 2 === 0) {
                    //Формула отвечающая за чередование
                    item.style.background = '#000';
                } else {
                    item.style.background = 'red';
                }
                chessWrap.appendChild(item);
            }
        }
    }

может кому понадобится

→ Ссылка