How to highlight alternate table row using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery :nth-child() selector

You can use the jQuery :nth-child() selector to create the zebra striped table by highlighting its alternate rows. The :nth-child(N) selector accepts these arguments — the index of each child to match (starting with 1), the string even or odd, or an expression (eg. :nth-child(2), :nth-child(even), :nth-child(2n).

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>Zebra Striped Table with jQuery</title>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         // Apply alt class on alternate table row
  •         $("table tbody tr:nth-child(2n)").addClass("alt");
  •     });
  • </script>
  • <style type="text/css">
  •     table{
  •         margin: 30px;
  •         border-collapse: collapse;
  •     }
  •     table tr{
  •         border-bottom: 1px solid #666;
  •     }
  •     table th, table td{
  •         padding: 10px;
  •     }
  •     /* Highlighter class */
  •     .alt{
  •         background: #cdcdcd;
  •     }
  • </style>
  • </head>
  • <body>
  •     <table>
  •         <thead>
  •             <tr>
  •                 <th>Row</th>
  •                 <th>First Name</th>
  •                 <th>Last Name</th>
  •                 <th>Email</th>
  •             </tr>
  •         </thead>
  •         <tbody>
  •             <tr>
  •                 <td>1</td>
  •                 <td>John</td>
  •                 <td>Carter</td>
  •                 <td>johncarter@mail.com</td>
  •             </tr>
  •             <tr>
  •                 <td>2</td>
  •                 <td>Peter</td>
  •                 <td>Parker</td>
  •                 <td>peterparker@mail.com</td>
  •             </tr>
  •             <tr>
  •                 <td>3</td>
  •                 <td>John</td>
  •                 <td>Rambo</td>
  •                 <td>johnrambo@mail.com</td>
  •             </tr>
  •             <tr>
  •                 <td>4</td>
  •                 <td>Harry</td>
  •                 <td>Potter</td>
  •                 <td>harrypotter@mail.com</td>
  •             </tr>
  •             <tr>
  •                 <td>5</td>
  •                 <td>Percy</td>
  •                 <td>Jackson</td>
  •                 <td>percyjackson@mail.com</td>
  •             </tr>
  •         </tbody>
  •     </table>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.