I began js 3 days ago at school, I had some C basics before so the main problem here would be the syntax (I think).
The goal is to produce a chessboard, 8x8 black and white square, but I can't get the code to show anything. What am I missing ?
(the html just have the script src="./x.js" part and the "body" part)
document.body.onload = addElement.innerHTML;
function addElement() {
var newTable = document.createElement("table");
for (var i = 1; i < 9; i++) {
var newTr = document.createElement('tr');
for (var j = 1; j < 9; j++) {
var newTd = document.createElement('td');
if (i % 2 == j % 2) {
newTd.className = "white";
} else {
newTd.className = "black";
}
newTr.appendChild(newTd);
}
newTable.appendChild(newTr);
}
document.body.appendChild(newTable);
document.getElementByClass("black").style.backgroundColor = "black";
document.getElementByClass("white").style.backgroundColor = "white";
document.getElementByTag("newTd").style.width = "25px";
document.getElementByTag("newTd").style.height = "25px";
}
chess. js is a Javascript chess library that is used for chess move generation/validation, piece placement/movement, and check/checkmate/stalemate detection - basically everything but the AI. chess. js has been extensively tested in node.
Use a table element. Each square is represented with a td element. Each row and column element is represented with a th. In the example I also added CSS to style the chess board.
There are few mistakes in your code use getElementsByClassName
instead of getElementByClass
and use getElementsByTagName
instead of getElementByTag
.
Also you need to loop over each selected elements.
Use window.onload = addElement;
or you can simply call addElement();
after function declaration completes.
window.onload = addElement;
function addElement() {
var newTable = document.createElement("table");
for (var i = 1; i < 9; i++) {
var newTr = document.createElement('tr');
for (var j = 1; j < 9; j++) {
var newTd = document.createElement('td');
if (i % 2 == j % 2) {
newTd.className = "white";
} else {
newTd.className = "black";
}
newTr.appendChild(newTd);
}
newTable.appendChild(newTr);
}
document.body.appendChild(newTable);
var i = 0;
for (i = 0; i < document.getElementsByClassName("black").length; i++) {
document.getElementsByClassName("black")[i].style.backgroundColor = "black";
}
for (i = 0; i < document.getElementsByClassName("white").length; i++) {
document.getElementsByClassName("white")[i].style.backgroundColor = "white";
}
for (i = 0; i < document.getElementsByTagName("td").length; i++) {
document.getElementsByTagName("td")[i].style.width = "25px";
document.getElementsByTagName("td")[i].style.height = "25px";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With