Styling alternate rows in HTML table

by Akram kamal

HTML

<div id="body">
    
<h2>Styling alternate rows in HTML table</h2>

    <hr/>
    
<h3>Table 1</h3>

    <table class="myTable">
        <tr>
            <td>As You Like It</td>
            <td>Comedy</td>
            <td>1600</td>
        </tr>
        <tr>
            <td>All's Well that Ends Well</td>
            <td>Comedy</td>
            <td>1601</td>
        </tr>
        <tr>
            <td>Hamlet</td>
            <td>Tragedy</td>
            <td>1604</td>
        </tr>
        <tr>
            <td>Macbeth</td>
            <td>Tragedy</td>
            <td>1606</td>
        </tr>
        <tr>
            <td>Romeo and Juliet</td>
            <td>Tragedy</td>
            <td>1595</td>
        </tr>
    </table>
    
<h3>Table 2</h3>

    <table class="myTable">
        <tr>
            <td>Hamlet</td>
            <td>Tragedy</td>
            <td>1604</td>
        </tr>
        <tr>
            <td>Macbeth</td>
            <td>Tragedy</td>
            <td>1606</td>
        </tr>
        <tr>
            <td>Romeo and Juliet</td>
            <td>Tragedy</td>
            <td>1595</td>
        </tr>
    </table>
</div>

CSS

/** Style for the body **/
 body {
    font: 12px Tahoma, Arial, Helvetica, Sans-Serif;
}
/** Main class for the alternate rows **/
 .alt {
    background-color:#eee;
}
/** Style for the table **/
 .myTable {
    border-collapse:collapse;
    font-size: 0.917em;
    max-width:500px;
    min-width:450px;
}
.myTable td {
    border:1px solid #333;
    padding:4px 8px;
}
.myTable td:nth-child(1) {
    width:200px;
}
.myTable td:nth-child(2) {
    width:150px;
}
.myTable td:nth-child(3) {
    width:100px;
}
/** Style for the cointainer **/
 #body {
    clear: both;
    margin: 0 auto;
    max-width: 534px;
}
html, body {
    background-color:White;
}
hr {
    margin-bottom:40px;
}

JavaScript

// Execute a function when the DOM is fully loaded.
$(document).ready(function () {

    // Set the .alt class for the alternate rows
    $('.myTable tr:nth-child(odd)').addClass('alt');
});