Keeping a list with alternate backgrounds when searching

1

I have a list with gray background in the item: nth-child (odd) but when I do a search is inserted a display none in the items that do not contain anything related and ends up messing the order of the colors, I need them to be rearranged accordingly with the search result

I put an example of the code in the codepen: link

    
asked by anonymous 20.11.2018 / 02:59

1 answer

1

I think only with CSS is not possible, since even and odd will also count the hidden elements.

One solution is to use a function to reapply backgrounds, and call it when you change the search result:

function evenOdd(){
   // seleciona apenas as divs filhas diretas de .wrapper-assoc que não for oculta
   var linhas = document.querySelectorAll(".wrapper-assoc > div:not([style*='display: none'])");
   var odd = "FFF";
   var even = "f30";
   for(var x=0; x < linhas.length; x++){
      if(x%2 != 0){
         linhas[x].style.background = "#"+even;
      }else{
         linhas[x].style.background = "#"+odd;
      }
   }
}

Lines that are not even are given the color of even , and others the color of odd .

You can use a ternary if you want instead of if :

linhas[x].style.background = "#"+ (x%2 != 0 ? even : odd);

Example:

function remover(){
   document.getElementById("linha3").style.display = "none";
   document.getElementById("linha6").style.display = "none";
   evenOdd();
}

function evenOdd(){
   var linhas = document.querySelectorAll(".wrapper-assoc > div:not([style*='display: none'])");
   var odd = "FFF";
   var even = "f30";
   for(var x=0; x < linhas.length; x++){
      linhas[x].style.background = "#"+ (x%2 != 0 ? even : odd);
   }
}
.wrapper-assoc > div:nth-child(even) {background: #f30}
.wrapper-assoc > div:nth-child(odd) {background: #FFF}
<button onclick="remover()">Ocultar linhas 3 e 6</button>
<div class="wrapper-assoc">
   <div>
      <div>1</div>
   </div>
   <div>
      <div>2</div>
   </div>
   <div id="linha3">
      <div>3</div>
   </div>
   <div>
      <div>4</div>
   </div>
   <div>
      <div>5</div>
   </div>
   <div id="linha6">
      <div>6</div>
   </div>
</div>

Fork of your CODEPEN

Denial pseudo-class compatibility :not() :

    
20.11.2018 / 03:47