Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issues with tr:odd in jquery

Tags:

jquery

css

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");  
}
like image 975
SammiA Avatar asked Aug 03 '16 19:08

SammiA


2 Answers

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.

like image 194
VoteyDisciple Avatar answered Nov 15 '22 12:11

VoteyDisciple


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>
like image 37
Ren Avatar answered Nov 15 '22 11:11

Ren