I'm trying to write this function where it will take users input from #rc and create a checker board of that size.
It works fine when n is an even number like 8, but if n is an odd number ,like 9, every "tr:2n+1" is colored wrong. what is the reason for this ? what should I do with it? Thank you in advance!
function setUpCheckBoard()
{
var n = $("#rc").val();
var stn= Number(n)+1;
var col = new Array(stn).join('<td></td>');
var row = new Array(stn).join('<tr>' + col + '</tr>');
$('tbody').append(row);
$("tr:odd td:odd").css("background-color", "black");
$("tr:odd td:even").css("background-color", "white");
$("tr:even td:odd").css("background-color", "white");
$("tr:even td:even").css("background-color", "black");
}
You want this:
$("tr:odd td:nth-child(2n+1)").css("background-color", "black");
$("tr:odd td:nth-child(2n)").css("background-color", "white");
$("tr:even td:nth-child(2n+1)").css("background-color", "white");
$("tr:even td:nth-child(2n)").css("background-color", "black");
The :odd
and :even
selectors don't care about the parent/child relationships of the selected elements; they select every other element out of all the matching elements.
So, you take tr:odd td
and get a bunch of td
elements from various rows of the table. When you do the :odd
ones of those, jQuery just counts through every other matching td
— some of which will be in the first column, and some of which will be in the second.
Using :nth-child(2n)
and :nth-child(2n+1)
specifically selects elements based on where they're positioned within their parent row.
Alternatively you may want the plain old CSS to handle it for you, like so:
<style type="text/css">
/* WHITE DEFAULT COLOUR */
table tr td {
background-color:white;
}
/* BLACK OVERRIDE COLOUR */
table tr:nth-child(even) td:nth-child(even), table tr:nth-child(odd) td:nth-child(odd) {
background-color:black;
}
</style>
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