0

I have a series of LI tags. Depending on how a user filters the LIs, some will be removed. I want to have the LIs alternate background color depending on what is visible.

For the ones that are visible, the class "LI-Shown" is added. If they get filtered out, I remove the LI-Shown class.

If I filter down, I could end up with this HTML:

<ul id="LI-List">
 <li id="1" class="LI-Shown">Showing</li>
 <li id="2" class="LI-Shown">Showing</li>
 <li id="3" style="display:none">Was Filtered Out</li>
 <li id="4" class="LI-Shown">Showing</li>
</ul>

My CSS looks like:

.LI-List .LI-Shown:nth-child(even) {
  background-color: gray;
}

The alternating background works when I load the results (or when all 4 LIs have LI-Shown). But when they get filtered down to what's above, the 2nd LI and 4th LI are both gray backgrounds. Even though I've removed the LI-Shown from the 3rd LI.

What it SHOULD do is: display only LI-Shown classes (IDs 1, 2, and 4). And only ID = 2 should be gray.

I can't figure out how to make the CSS treat that 4th LI as a 3rd LI-Shown class. :( It needs to get rid of the gray background color and revert it to the default.

I have also tried using jquery directly to do it with:

$('.LI-List .LI-Shown').filter(":even").css('background', 'gray');

Thanks in advance for any help.

ktstar
  • 77
  • 1
  • 9
  • one typo from your code is , LI-list is id , show you should use #LI-list instead of .LI-list and can you confirm whether li with id =3 also have class = LI-shown or not? – Naga Sai A Jul 29 '19 at 17:08

1 Answers1

0
  1. In <ul> you need class instead of id <ul id="LI-List">
  2. Nth-Child/Nth-Of-Type can't be used with class. Nth-Child use DOM hierarchy, Nth-Of-Type use tags type (p, div, span, etc.)
  3. Here jQuery solutuion:

$('.LI-List .LI-Shown').filter(":even").css('background', 'gray');
.LI-Hidden {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="LI-List">
 <li id="1" class="LI-Shown">Showing</li>
 <li id="2" class="LI-Shown">Showing</li>
 <li id="3" class="LI-Hidden">Was Filtered Out</li>
 <li id="4" class="LI-Shown">Showing</li>
</ul>
imkremen
  • 84
  • 4