c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
JavaScript

Html table alternate row Highlight using JavaScript

| | JavaScript

If we want to highlight the html table alternate row using javascript.We need to get collection of all elements specified with TR tag by getElementByTagName and the method will return as object.

Loop each row until the end of the tag element in collection object. I have written some logic to find odd number, if it matches then make it as highlighted by using class name highlight. 

Example:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function () {
            $("#btnChange").click(function () {
                var tr = document.getElementsByTagName("tr");
                for (var i = 0; i <tr.length; i++) {
                   isOdd(i);
                   if (isOdd(i)) {
                       tr[i].className = 'highlight';
                   }
               }
            });
        });
        function isOdd(num) {
            return num % 2;
        }
    </script>
    <style type="text/css">
        td {
            border-bottom: 1px solid #808080;
        }
        .highlight {
            background-color: #2a78ac;
           color: white;
        }      
    </style>
</head>
<body style="font-family: Arial; width: 500px; border: 1px solid #e5dddd">
    <table>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
        </tr>
        <tr>
            <td>Ashton Cox</td>
            <td>Junior TechnicalAuthor</td>
            <td>San Francisco</td>
           <td>42</td>
        </tr>
        <tr>
            <td>Cedric Kelly</td>
            <td>Senior JavascriptDeveloper</td>
            <td>Edinburgh</td>
            <td>22</td>
        </tr>
        <tr>
            <td>Airi Satou</td>
            <td>Accountant</td>
          <td>Tokyo</td>
            <td>33</td>
        </tr>
        <tr>
            <td>BrielleWilliamson</td>
            <td>IntegrationSpecialist</td>
            <td>New York</td>
            <td>61</td>
        </tr>
    </table>
    <button id="btnChange">show highlight alternate row</button>
</body>
</html> 

Click the button I m sure html table alternate row will hightlight as below result. 

Output: