Here is the javascript function:
function chessBoard(size) {
let html = `<div class="chessboard">\n`;
for (let row = 0; row < size; row++) {
html += ` <div>\n`;
let color = (row % 2 == 0) ? "black" : "white";
for (let col = 0; col < size; col++) {
html += ` <span class="${color}"></span>\n`;
color = (color == "white") ? "black" : "white";
}
html += ` </div>\n`;
}
return html + `</div>`;
}
//chessBoard(4);//to test in the console
The HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="yourjsfile.js"></script>
<link rel="stylesheet" href="yourcssfile.css">
</head>
<body>
<script>
let html = chessBoard(3);
document.body.innerHTML = html;
</script>
</body>
</html>
and the CSS file:
body{
background: #ddd;
}
.chessboard {
display: inline-block;
}
div {
}
span {
display: inline-block;
width: 70px;
height: 70px;
}
.black {
background: black;
}
.white {
background: white;
}