2

I have a table with n rows. On these n rows I need to set some CSS style, following this rules:

  • the CSS should apply only on odd rows
  • the CSS should NOT apply on the first and the last row (or on those rows with .excludeme class)
  • the CSS should apply only on visible rows

HTML

<table>
    <tr class="excludeme"><td>first</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr class="showhide"><td>show/hide</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr><td>Hello</td></tr>
    <tr class="showhide"><td>show/hide</td></tr>
    <tr class="showhide"><td>show/hide</td></tr>
    <tr><td>Hello</td></tr>
    <tr class="excludeme"><td>last</td></tr>
</table>

CSS

.showhide{
    display: none;
}
table tr:nth-child(odd):not(.excludeme){
    background: orange;
}

JS

//--- #test is a button
$("#test").on("click", function(){
   $(".showhide").toggle(); 
});

you can find a fiddle HERE

As you can see, when some rows are hidde, the even/odd colouring is not respected. I tried this selector

table tr:nth-child(odd):not(.excludeme):visible{
    ....
}

but is not working.. Is it possible to accomplish this only using CSS?

Thank you

BeNdErR
  • 17,471
  • 21
  • 72
  • 103

2 Answers2

0
$(document).ready(function(){
    $("#test").on("click", function(){
       $(".showhide").toggle();
        if($(element).is(":visible")){
            // color odd rows
        }
    });
});

You have to verify the visibility of elements before coloring them. Only color the visible odd elements, not all elements in DOM (visible or not).

I hope that helps, have a good day :)

dustfeather
  • 86
  • 1
  • 8
0

you can use following CSS(use of gradient CSS) without changing any other code:

* {
    margin: 0;
    padding: 0;
}
table {
    padding: 0;
    margin: 0;
    border: none;
    width: 100%;
    background-image:
    repeating-linear-gradient(white, white 1.2em, hotpink 1.2em, hotpink 2.4em);
    border-collapse: collapse;

}
td,tr {
    border: none;
    padding: 0 5px;
    line-height: 1.2em;
    margin: 0;
    border-collapse: collapse;
}
.showhide {
   display: none;
}

.excludeme {
     background: white;
}
Dipali Vasani
  • 2,526
  • 2
  • 16
  • 30