css nth-child(2n+1) repaint css after filtering out list items

Michael picture Michael · Jul 26, 2012 · Viewed 8.4k times · Source

I have a list of 20+ items. The background-color changes using the :nth-child(2n+1) selector. (ie. even item black, odd item white). When I click a button to filter out specific items using the jQuery Isotope plugin it adds a .isotope-hidden class to the items I want to filter out, which changes the position of the list item to 0,0 and opacity to 0.

When this happens the remaining items are left with the original black/white background-colors, which are now no longer in order.

Does anyone know a way to "repaint' the css using the :nth-child(2n+1) selector on the items that do not contain the .isotope-hidden class.

I tried

#element tr:not(.isotope-hidden):nth-child(2n+1)

with no avail.

Any help would be appreciated. Thank you.

Answer

Stephen Saucier picture Stephen Saucier · Oct 26, 2012

Nth-child can be counterintuitive when working with a filtered selection of a group.

Use .each() to get around its limitations:

var count = 1;
$('#element tr:not(.isotope-hidden)').each(function(){
    if ( count++ % 2 == 1 ) $(this).css('background-color','white')
})