I think only with CSS is not possible, since the even
and the odd
will also tell the hidden elements.
One solution is to use a function to reapply backgrounds, and call it when changing 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 receive the color of the even
, and the others the color of odd
.
You can wear 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
Compatibility of the negation pseudo-class :not()
:
Sam, a great solution, but had already considered using the :not() selector, but seeing its compatibility in caniuse became unviable for the project...
– Renan Hugo
I know. You can tell me what Caniuse accused of incompatibility?
– Sam
Exactly, it is not yet well supported, https://caniuse.com/#search=%3Anot
– Renan Hugo
I think you’re wrong. The dial
:not()
with CSS selectors is widely supported. It even works on Safari for Windows discontinued in 2012.– Sam
But there is another way to do the same thing, just select all the elements without the :not and check in the loop if the div has style="display: None;", but it’s not even worth doing since the
:not([style*='display: none'])
is compatible with all browsers, including IE 9+.– Sam