The code in the first Code Block is the source code. After the source code is running. The code will be changed (See the 2nd Code Block).
I want the class(i.e. 'even' and 'odd') of tag is only displayed in the 'table1'. However, currently a nest table (i.e. 'table2') also has 'even' and 'odd' class of each tag.
Can anyone help me out? Thanks in advance.
-----------First Code Block--------------
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#table1 tr:odd").addClass("odd");
$("#table1 tr:not(.odd)").addClass("even");
});
</script>
</head>
<body>
<table id="table1">
<tr>
<td>AAA</td>
<td>CCC</td>
</tr>
<tr>
<td>BBB</td>
<td>DDD</td>
</tr>
<tr>
<td>
<table id="table2">
<tr></tr>
<tr></tr>
<table>
</td>
</tr>
</table>
</body>
-----------2nd Code Block---------------
<table id="table1">
<tr class="even">
<td>AAA</td>
<td>CCC</td>
</tr>
<tr class="odd">
<td>BBB</td>
<td>DDD</td>
</tr>
<tr class="even">
<td>
<table id="table2">
<tr class="even"></tr>
<tr class="odd"></tr>
<table>
</td>
</tr>
</table>
The :odd selector selects each element with an odd index number (like: 1, 3, 5, etc.). The index numbers start at 0. This is mostly used together with another selector to select every odd indexed element in a group (like in the example above).
Use “tr: odd” to select the odd data & use “tr: even” to select the even data in the row.
Approach 2: Use $('table tr:last') jQuery Selector to find the last element of the table. The 'table' in query looks for the table element then 'tr' is looking for all the rows in the table element and ':last' is looking for the last table row of the table.
The even() method in jQuery is used to select the even indexed elements from the selected elements. Syntax: $(selector).even() Return Value: It returns the even indexed elements. Example 1: This example selects the even indexed list elements.
All of the posted answer are almost right..
$(document).ready(function(){
$("#table1 > tbody > tr:odd").addClass("odd");
$("#table1 > tbody > tr:not(.odd)").addClass("even");
});
Many browsers automatically add a tbody
to your table even if you don't add one yourself. So #table1 > tr
will not match because tr
is not a direct child of table
. Your best bet is to use the above and explicitly add a tbody
for those browsers that don't do it for you.
<table id="table1">
<tbody>
<tr class="even">
<td>AAA</td>
<td>CCC</td>
</tr>
<tr class="odd">
<td>BBB</td>
<td>DDD</td>
</tr>
<tr class="even">
<td>
<table id="table2">
<tbody>
<tr class="even"></tr>
<tr class="odd"></tr>
</tbody>
<table>
</td>
</tr>
<tbody>
</table>
http://jsfiddle.net/5ETAD/1/
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