SammiA SammiA - 4 months ago 7
CSS Question

issues with tr:odd in jquery

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");
}

Answer

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.