I have created a chess board using a table element and I want to get all the divs so I can see it printed in the console
Since there are 64 squares I want to see them all listed in the the console so I can make an array from it, but what I get instead is HTMLCollection [div#id, id: div#id]
. How could i get it to console out all the elements in it?
let div = document.getElementsByClassName('board')
div[0].setAttribute('id', 'divid')
let divId = document.getElementById('divid')
var table = document.createElement("div");
table.id = 'id'
let id=0;
for (var i = 1; i < 9; i++) {
var tr = document.createElement('tr');
for (var j = 1; j < 9; j++) {
var td = document.createElement('td');
id++
td.id = id
if (i % 2 == j % 2) {
td.className = "white";
} else {
td.className = "black";
}
tr.appendChild(td);
}
table.appendChild(tr);
}
divId.appendChild(table)
console.log(divId.children)
<div class="board"></div>
>Solution :
Why div and tr?
This makes more sense.
Also I give the cells the proper chess ID
const hor = "ABCDEFGH";
const table = document.getElementById("board");
let id = 0;
for (let i = 0; i < 8; i++) {
let tr = document.createElement('tr');
for (let j = 0; j < 8; j++) {
let row = hor[j];
let cell = 8-i
let td = document.createElement('td');
td.id = `${row}${cell}`
// td.textContent = td.id
td.className = (i % 2 == j % 2) ? "white" : "black";
tr.appendChild(td);
}
table.appendChild(tr);
}
const arr = table.querySelectorAll('td');
// set A4 to red
document.getElementById('A4').classList.toggle('red');
// set the 16th entry to blue (JS array start at 0)
document.getElementById(arr[15].id).classList.toggle('blue');
// pawn to E4
//document.getElementById("E4").classList.toggle('pawn'); // not implemented yet here
document.getElementById("E4").innerHTML = `<i class="fas fa-chess-pawn" style="font-size:24px" aria-hidden="true"></i>`
console.log(JSON.stringify([...arr].map(cell => cell.id)))
table {
border: 1px solid black;
border-collapse: collapse;
}
#board td {
height: 50px;
width: 50px;
}
.white {
background-color: white;
color: black;
text-align: center;
/* vertical-align: top; */
}
.black {
background-color: black;
color: white;
text-align: center;
/* vertical-align: top; */
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" />
<table>
<tbody id="board"></tbody>
</table>