I am learning how to code and unfortunately, I am stuck on one exercise.
I have a table
containing 2 different rows of colors, and I want to invert the colors — the tr
class .vermelho
needs to be .azul
, and .azul
to be .vermelho
.
I tried the following JS code, but it’s setting the whole table
with a single color. Would you please be so kind to help me identify the error on the JS code? Sorry for any English typo I am not native:
function invertStyle() {
if ($('.vermelho').hasClass('vermelho')) {
$('.vermelho').removeClass('vermelho').addClass('azul');
} else if ($('.azul').hasClass('azul')) {
$('.azul').removeClass('azul').addClass('vermelho');
}
}
table {
border-collapse: collapse;
text-align: center;
width: 100px;
}
.vermelho {
background-color: red;
}
.azul {
background-color: blue;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<table id="tabela">
<tr>
<th>Nome</th>
<th>Idade</th>
</tr>
<tr class="azul">
<td>João</td>
<td>40</td>
</tr>
<tr class="vermelho">
<td>Maria</td>
<td>50</td>
</tr>
<tr class="azul">
<td>Ana</td>
<td>20</td>
</tr>
<tr class="vermelho">
<td>Pedro</td>
<td>10</td>
</tr>
<tr class="azul">
<td>Lúcio</td>
<td>25</td>
</tr>
<tr class="vermelho">
<td>Júlia</td>
<td>15</td>
</tr>
</table>
<input type="button" value="Inverter estilo" onClick="invertStyle()" />
2
Answers
I ended up using the following JS code, and it worked:
Select all
tr
except the first row, and toggle the class on each click.Please see the code snippet below. In short, I’ve solved like the following:
tr
rows in a variablerows
tr
list to check their current class name.azul
, make itvermelho
.azul
(i.e. it’svermelho
), make itazul
.I tried to make everything self-explanatory, and the only potentially confusing thing might be the ternary operator. See MDN Docs for Ternary Conditional.