简体   繁体   中英

I am writing a Javascript function to to color every other row in a table a different color. Why doesn't my code work?

My understanding of the function I've written is that any table will be subject to this function through the getElementsByTag selector.

Then, the row count is detected to allow for traversal in the for loop.

Then the current row is defined by "row" and if the current i value is odd, the row will be colored red.

But that is not what is happening so I was hoping for some insights, please?

function tableHighlight(){  
    var table = document.getElementsByTagName("table");
    var rowCount = table.rows.length;

        for(var i=1; i<rowCount; i++) {
             var row = table.rows[i];
         if(i%2 != 0){
            row.style.background="#000000";
        }
         }
}

when you use getElementsByTagName, it returns you a list

function tableHighlight(){  
    var table = document.getElementsByTagName("table")[0];
    var rowCount = table.rows.length;

        for(var i=1; i<rowCount; i++) {
             var row = table.rows[i];
         if(i%2 != 0){
            row.style.background="#000000";
        }
         }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM