tags:

views:

27

answers:

1

I'm having trouble figuring out how to maintain my table stripes after adding new rows to a table. If I change the .insertAfter() selector to #names tr:last it works as I would expect, however using tr:first or tr:nth-child(x) results in the new row and all rows below it being striped. When looking at the updated DOM in Chrome's developer tools everything looks normal. I'm hoping someone can explain to me why this isn't working. I feel like I must be missing something fundamental. Here's the code:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            .striped {
                background-color: #silver;
            }
        </style>

        <script type="text/javascript" src="jquery-1.4.3.js"></script>
        <script type="text/javascript">
            function stripes () {
                $("tr:even").each(function () {
                    $(this).addClass("striped");
                });
            }

            $(function () {
                stripes();
                $("#addRow").click(function () {
                    $("<tr><td>Kenny</td><td>Bania</td></tr>").insertAfter("#names tr:first");
                    stripes();
                });
            });
        </script>
    </head>
    <body>
        <div>
            <a href="#" id="addRow">Add Row</a>
            <table>
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </tr>
                </thead>
                <tbody id="names">
                    <tr>
                        <td>Jerry</td>
                        <td>Seinfeld</td>
                    </tr>
                    <tr>
                        <td>Elaine</td>
                        <td>Benes</td>
                    </tr>
                    <tr>
                        <td>George</td>
                        <td>Costanza</td>
                    </tr>
                    <tr>
                        <td>Cosmo</td>
                        <td>Kramer</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>

Thanks!

+1  A: 

You need to remove .striped class first.

function stripes () {
            $("tr").each(function () {
                $(this).removeClass("striped");
            });
            $("tr:even").each(function () {
                $(this).addClass("striped");
            });
        }
Shelvin
Wow that should have been apparent. Thank you!
Terminal Frost
Why are we calling each? jQuery doesn't need to iterate over the entire collection. $('tr').removeClass('striped'); $('tr:even').addClass('striped'); is all you need
Samo