2

HTML:

<table border="1"style="width:500px" id="table2">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>grades</th>
  </tr>
  <tr>
    <td>riddhi</td>
    <td>bhatt</td>
    <td>50</td>
  </tr>
  <tr>
    <td>sneh</td>
    <td>pandya</td>
    <td>55</td>
  </tr>
  <tr>
    <td>ankit</td>
    <td>purani</td>
    <td>60</td>
  </tr>
</table>

I want to add a background color in odd rows of table.

JQuery:

$(document).ready(function(){

    $("#table2 > tr:odd").css("background-color","blue");
});

I am new in HTML and jQuery, please suggest me so that I can proceed...

6 Answers 6

3

Use this ,

$(document).ready(function(){

    $("#table2 tr:odd").css("background-color","blue");
});

Demo Fiddle

> won't work here - Reference


The table hierarcy is table > tbody > tr > td, so in that case, try this,

 $("#table2 > tbody > tr:odd").css("background-color","blue");

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

As others said,

$("#table2 tr:odd")

will select ALL of the odd tr's inside table2, it'll work for a simple table. But if you want to for example put a table inside table2, it will select the trs of the second table too, because they're also inside table2

if you want to select only the tr's from table2, but not the ones of a table inside table2, you would use

$("#table2>tbody>tr:odd")

which selects only the direct tr children of the direct tbody children of table2

Comments

0

Try this

$("#table2 tr:odd").css("background-color","blue");

DEMO

Comments

0

tbody, thead and tfoot is rendered by html so you need to use #table2 > tbody > tr:odd,#table2 > thead > tr:odd,#table2 > tfoot > tr:odd as a selector to make it work but you have no sense to use odd here. So simple if you just remove > then it will be fine:

$("#table2 tr:odd").css("background-color","blue");

Comments

0

IF none of the above working means please try to Change $ to jQuery, it will be work...

1 Comment

this is not a solution.When there is conflict u need to use your solution
0

It works fine: http://jsbin.com/caxahube/1/edit

$(document).ready(function(){

  $('table>tbody>tr:odd').css('background-color', 'blue');

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.