user6290240
user6290240

Reputation:

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>

Upvotes: 0

Views: 57

Answers (2)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

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

Upvotes: 1

brk
brk

Reputation: 50291

As answered by Jeremy J Starcher you can use className to add a class to an element generated using javascript.

But you can also you classList property, which return a list of class attached to the element.

It has two useful method add & removea class from the element.

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 + ')';
            //Changed here
            boardSquare.classList.add((row + col) % 2 == 0 ? 'whiteSquare' : 'blackSquare');
            //boardSquare.innerHTML = boardSquare.class;
        }
    }
}

generateBoardHTML();

Check this jsFiddle

Upvotes: 1

Related Questions