45

Is there a way to only affect visible elements with this css?

table.grid tr.alt:nth-child(odd)
{
    background:#ebeff4;
}

table.grid tr.alt:nth-child(even)
{
    background:#ffffff;
}

If i use a $('select some tr:s').hide() that hides some of the rows i get a mix of odd and even styling but all in a mixup.

Andreas
  • 6,958
  • 10
  • 38
  • 52
  • 4
    Have you considered reapplying the CSS after the $().hide() using $('.alt:visible:even') and $('alt:visible:odd')? – Rodaine Jul 08 '11 at 19:45

3 Answers3

20

I ended up using the solution Rodaine suggested in his comment, after the show/hide i do this:

$('.alt:visible:odd').css('background', '#EBEFF4');
$('.alt:visible:even').css('background', '#FFFFFF'); 

In my case the setting of background broke my hover, this was solved with !important to make the hover background stick.

table.grid tr.hover:hover
{
    cursor:pointer;
    background:#D2E0E9 !important;    
}
Andreas
  • 6,958
  • 10
  • 38
  • 52
  • 4
    Using !important in production environnment is not a good habit to have. If you end up using !important, it means the solution may be a bit more complicated, but it exists. In that case, you want to apply classes with jquery to still be able to hover without !important : http://codepen.io/gfra/pen/nFrEc – Gfra54 May 29 '14 at 07:54
  • Sometimes when using external libraries you don't have any choice in using "!important" – LarryBud Dec 26 '21 at 15:32
-2

Another option would be to apply a class to the visible elements when hiding the others. Apply nth-child to this class (which is only applied to the visible elements.)

You don't have to use an !important tag to keep your hover-background in this case.

  • That's not possible, unfortunately: http://stackoverflow.com/questions/5428676/nth-child-doesnt-respond-to-class – Christoffer May 27 '15 at 17:57
-5

You could do:

$('some_selector tr:visible').hide()

Hope this helps

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61