Josh Thieme Josh Thieme - 6 months ago 10
HTML Question

How do I use css to style an element which has a JS-generated classname?

I'm currently trying to port a long-running pet project of mine (A Java chess application) to the web using HTML/CSS/JS, but am not very experienced in web development.
What I want to do is use the classname of my board squares ( elements) to denote what color they should be set to by the css.
The elements are all JS-generated as shown in my code snippet, and I have verified that each square's classname is being correctly set. The CSS doesn't seem to be changing the background color properly however.

Any tips/pointers appreciated :)





function generateBoardHTML() {
var chessBoard = document.getElementById('chessBoard');

for (var row = 0; row < 8; row++) {
var boardRow = chessBoard.insertRow(row);

for (var col = 0; col < 8; col++) {
var boardSquare = boardRow.insertCell(col);

boardSquare.id = '(' + row + ',' + col + ')';
boardSquare.class = (row + col) % 2 == 0 ? 'whiteSquare' : 'blackSquare';
//boardSquare.innerHTML = boardSquare.class;
}
}
}

generateBoardHTML();

td {
border: 1px solid black;
width: 80px;
height: 80px;
}

.whiteSquare {
background-color: white;
}

.blackSquare {
background-color: black;
}

<table id='chessBoard'>
<tbody></tbody>
</table>




Answer

There are several CSS properties that have weird names when you reference then in JavaScript. class is one of them. (for is the other, which becomes labelFor.)

boardSquare.className = (row + col) % 2 == 0 ? 'whiteSquare' : 'blackSquare';

Historical note: Under ES3 you cannot use reserved words as property names and class is a reserved word. While this doesn't matter in ES5, this convention is already pretty much set in stone.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/className