views:

85

answers:

1

Hi all,

Today it came to my attention that a combination of jQuery selectors and the addClass() function does not work properly on IE8.

For example, when I want to ensure that even-numbered rows are selected in a table, I wrote:

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

And for the CSS, I wrote:

#table1 tr:nth-child(even), #table1 tr.even {
    background-color: #ff0;
}

In Firefox, Chrome, Safari and Opera, even without the pseudo-class selector in the CSS file, even-numbered rows are selected. However, in IE8, it is not the case. The rows don't have a different background color.

This is weird because when I used:

jQuery(document).ready(function($){
    $("#table1 tr:nth-child(even)").css({"background-color":"#ff0"});
}

The selected rows are highlighted in IE8.


An example of the problem is question can be seen here - 24ways example. In Firefox, Chrome, Safari and Opera, the odd rows are assigned an "odd" class. However, in IE8, they are not assigned an "odd" class and are not highlighted.

+3  A: 

The selector works correctly on the jQuery side...but IE8 seems to be discarding this style rule entirely:

tr:nth-child(odd) td, tr.odd td {
  background-color: #86B486;
}

If you split it, it'll work correctly:

tr:nth-child(odd) td {
  background-color: #86B486;
}
tr.odd td {
  background-color: #86B486;
}

I'm not sure why IE8 is behaving this way, but that's the case. Here's the original version (a single rule IE8 removes) and here's a fixed sample, with the rule split.


For completeness sake, reversing the rule like this doesn't help:

tr.odd td, tr:nth-child(odd) td {
  background-color: #86B486;
}
Nick Craver
Nick, thank you so much for the fix. It worked like magic. It's indeed puzzling why IE8 behaves this way, because for other pseudo selectors it doesn't happen. For example, when I used first-child and last-child pseudo selectors in jQuery, it still works as intended.Thanks again!
teddyrised
@teddyrised - Welcome :) I'm not sure why IE behaves like this, I'll just add it to the list of 50,000 things it does wrong. As an aside, be sure to accept answers to close out the question/help the next guy finding this issue on google - via the checkmark on the left :)
Nick Craver
Ah, many thanks for the help. I'm still new to stack overflow although I've been lurking around forever. Thanks!
teddyrised