I'm writing an html page with some jQuery for style. So I have the following:
$("table tr:odd td").css({"background-color":"rgb(233,247,255)"});
This makes every other row bluish. But just now, I put a table inside one of the cells. What happened? Well, it treated the row of the inner table as if it was a row in the outer table, and the coloring got messed up (two consecutive blue rows, while the row in the inner table was left white).
So, how do I exclude sub-tables in a selector like this? Anyone?
EDIT:
Thanks for your ideas and answers. I came up with this bit of code, because what I really want is to have all tables have even/odd coloring (not just top-level tables):
$("table").each(function()
{ $(this).children().children(":odd").css({"background-color":"rgb(240,255,250)"});
$(this).children().children(":even").css({"background-color":"rgb(233,247,255)"});
});
The problem is that this seems to only color the first row - I have no idea why. Does anyone see why?
SOLUTION: I figured it out. The problem is that browsers do in fact insert a tbody tag, and you have to figure it in. Heres the final result i'm using:
$("table").each(function()
{ $(this).children().children(":odd").children().css({"background-color":"green"});
$(this).children().children(":even").children().css({"background-color":"blue"});
});
You can use the child selector >
. They browser should insert a tbody
element though:
$("#myTable > tbody > tr:odd > td").css({"background-color":"rgb(233,247,255)"});
Russ Cam inspired me to answer the question again without using an identifier on the table and this is what I came up with:
$("table:not(td > table) > tbody > tr:odd > td").css({"background-color":"rgb(233,247,255)"});
Here I select all td's, in every odd row, in tables that are not children of a <td>
. Working demo here.
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