Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Can't make nth-child work with IE8

Can't make nth-child work with IE8

Problem

I have the following to alternate colors in a table:

#grid tr:nth-child(odd)    { background-color:#eee; }
#grid tr:nth-child(even)   { background-color:#fff; }

However, this works in Firefox, but not in IE8. After some research, I tried the following:

CSS:

#grid tr.odd    { background-color:#eee; }
#grid tr.even   { background-color:#fff; }

jQuery:

$(document).ready(function() {
    $("#grid tr:nth-child(even)").addClass("even");
    $("#grid tr:nth-child(odd)").addClass("odd");
});

But it doesn't work (actually, it didn't even work in Firefox). Any ideas of what else I could do (without having to use a third party js, such as Selectivizr)?

Thank you!

Problem courtesy of: Anna

Solution

I was able to get it to work using jQuery by looping through each tr element and adding the class based on the index being odd/even

I tested with my a test web app with IE8, then I copied my code from the test app to jsFiddle. Only to realize that jsFiddle does not work properly with IE8.

WORKING JSFIDDLE

JS:

$(function () {
    $('tbody').children().each(function (index) {
        var row = $(this);
        if ((index + 1) % 2 === 0) {                
            row.addClass("even");
        } else {                
            row.addClass("odd");
        }
    });
});

HTML:

Col 1 Col 2 Col 3 Col 4 Col 5
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Col 1 data Col 2 data Col 3 data Col 4 data Col 5 data
Solution courtesy of: Charles380

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Can't make nth-child work with IE8

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×