Reputation: 827
I have a HTML table like this.
<table class="TableA">
<tbody>
<tr>
<td>1</td>
<td class="a">aa</td>
</tr>
<tr>
<td>2</td>
<td class="a">aa</td>
</tr>
<tr>
<td>3</td>
<td class="a">bb</td>
</tr>
<tr>
<td>4</td>
<td class="a">cc</td>
</tr>
<tr>
<td>5</td>
<td class="a">dd</td>
</tr>
<tr>
<td>6</td>
<td class="a">ee</td>
</tr>
<tr>
<td>7</td>
<td class="a">ee</td>
</tr>
</tbody>
</table>
How can i alternating color by column <td class="a">
value html?
This result like this
I have tried this JS code.
My idea is to find all ("td.a")
and compare string. If true bgColor = "red"
.
$(".TableA").each(function () {
if ($(this).find("td.a")[0].innerHTML == $(this).find("td.a")[1].innerHTML) {
$(this).find("td.a")[0].bgColor = "red";
} else {
$(this).find("td.a")[0].bgColor = "white";
}
});
Upvotes: 1
Views: 81
Reputation: 142
If you want to make two sibling td
that has same innerHTML to be red background, you can try this code, it's easy to understand:
const testArray = $(".TableA td.a")
testArray.map(function(index) {
// Be careful out of the array
if (index === testArray.length - 1) return 0;
if (
testArray[index].innerHTML ===
testArray[index + 1].innerHTML
) {
testArray[index].style.background = "red";
testArray[index + 1].style.background = "red";
} else {
testArray[index].style.background = "white";
}
});
Upvotes: 0
Reputation: 10227
To highlight consequence rows with same text, you can use the next()
to compare the next element and add class accordingly.
$(".TableA tr").each(function() {
let now = $(this).find('td').last();
let next = $(this).next().find('td').last();
if (now.text() == next.text()) {
now.addClass('red');
next.addClass('red');
}
});
.red {
background: red;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<table class="TableA">
<tbody>
<tr>
<td>1</td>
<td class="a">aa</td>
</tr>
<tr>
<td>2</td>
<td class="a">aa</td>
</tr>
<tr>
<td>3</td>
<td class="a">bb</td>
</tr>
<tr>
<td>4</td>
<td class="a">cc</td>
</tr>
<tr>
<td>5</td>
<td class="a">dd</td>
</tr>
<tr>
<td>6</td>
<td class="a">ee</td>
</tr>
<tr>
<td>7</td>
<td class="a">ee</td>
</tr>
</tbody>
</table>
Upvotes: 2