Modified following a suggestion
To simplify the process, add a specific class to the table itself along with an index value. Then, you can easily apply CSS rules to style the elements without the need for excessive looping.
By doing this, you can utilize a pseudo-element to cover each cell, as shown below:
$(document).ready(function() {
$('table').on('click', function(e) {
$(this).attr('class', 'idx' + $(e.target.parentElement).children().index(e.target));
});
});
td {
position: relative;
border: 1px solid gray;
}
table.idx0 td:nth-child(-n+0)::after,
table.idx1 td:nth-child(-n+1)::after,
table.idx2 td:nth-child(-n+2)::after,
table.idx3 td:nth-child(-n+3)::after,
table.idx4 td:nth-child(-n+4)::after,
table.idx5 td:nth-child(-n+5)::after {
content: '';
position: absolute;
left: -2px; /* 2px to make up for border/padding */
top: -2px;
height: calc(100% + 4px);
width: calc(100% + 4px);
background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
<th>c5</th>
<th>c6</th>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
</table>
Alternatively, you can simply set both text color and background color to be the same:
$(document).ready(function() {
$('table').on('click', function(e) {
$(this).attr('class', 'idx' + $(e.target.parentElement).children().index(e.target));
});
});
td {
border: 1px solid gray;
}
table.idx0 td:nth-child(-n+0),
table.idx1 td:nth-child(-n+1),
table.idx2 td:nth-child(-n+2),
table.idx3 td:nth-child(-n+3),
table.idx4 td:nth-child(-n+4),
table.idx5 td:nth-child(-n+5) {
background: black;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
<th>c4</th>
<th>c5</th>
<th>c6</th>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
<td>d4</td>
<td>d5</td>
<td>d6</td>
</tr>
</table>