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 <tr> tag is only displayed in the 'table1'. However, currently a nest table (i.e. 'table2') also has 'even' and 'odd' class of each <tr> tag.

Can anyone help me out? Thanks in advance.

<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>
<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>

Dani AI

Generated

Short answer: limit the selection to the top-level rows inside #table1 (and account for the browser-inserted tbody). was right about using a child selector in principle, but most browsers place the TRs under a tbody, so selecting direct children of the TABLE without including tbody will miss the real DOM structure.

A robust jQuery approach that avoids touching nested tables is to target the TRs under #table1's tbody and add classes based on the row index. For example:

$("#table1").children("tbody").children("tr").each(function(i){
  $(this).addClass(i % 2 ? "odd" : "even");
});

If the goal is purely visual striping, CSS can do this without JS and also avoid nested rows:

#table1 > tbody > tr:nth-child(even) { background:#f8f8f8; }
#table1 > tbody > tr:nth-child(odd)  { background:#ffffff; }

Notes and troubleshooting:

  • The sample HTML in 's post has malformed markup (missing a closing </table>). Broken HTML can change the DOM and make selectors behave unexpectedly; validate the markup first.
  • Remember jQuery’s index-based selectors: counting starts at 0 (so index 0 is "even"). That can make :odd/:even feel counterintuitive.
  • For details on the tbody insertion and proper child selectors see the MDN tbody entry and the jQuery .children() docs: MDN: tbody and jQuery .children().

You need the child selector, not the descendant selector;

$("#table1 > tr:odd").addClass("odd");
                $("#table1 > tr:not(.odd)").addClass("even");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.