Skip to content

Instantly share code, notes, and snippets.

@marianoviola
Created November 21, 2018 08:25
Show Gist options
  • Save marianoviola/8caaef52373826b04bbd04e1141db5fa to your computer and use it in GitHub Desktop.
Save marianoviola/8caaef52373826b04bbd04e1141db5fa to your computer and use it in GitHub Desktop.
Columns Painter πŸ›πŸ–
<table>
<caption>Favorite and Least Favorite Things</caption>
<tbody>
<tr>
<th></th>
<th></th>
<th>Bob</th>
<th>Alice</th>
</tr>
<tr>
<th rowspan="2">Favorite</th>
<th>Color</th>
<td>Blue</td>
<td>Purple</td>
</tr>
<tr>
<th>Flavor</th>
<td>Banana</td>
<td>Chocolate</td>
</tr>
<tr>
<th rowspan="2">Least<br>Favorite</th>
<th>Color</th>
<td>Yellow</td>
<td>Pink</td>
</tr>
<tr>
<th>Flavor</th>
<td>Mint</td>
<td>Walnut</td>
</tr>
</tbody>
</table>
const rows = document.querySelectorAll('table tr')
const maxCells = Math.max(...Array.from(rows).map(row => row.children.length));
const cell = 1;
const color = 'pink';
let span = null;
let spanner = null;
rows.forEach((row, i) => {
const currentCell = row.children[cell];
const cellsNo = row.children.length;
const diff = maxCells - cellsNo;
if (currentCell && currentCell.hasAttribute('rowspan')) {
span = parseInt(currentCell.getAttribute('rowspan'));
spanner = i;
currentCell.style.backgroundColor = color;
}
if (span && i > spanner + span) {
currentCell.style.backgroundColor = color;
}
if (!span) {
const trueCell = cell > 0 ? cell - diff : cell;
row.children[trueCell].style.backgroundColor = color;
}
});
table {
border-collapse: collapse;
color: darkviolet;
}
table, th, td {
border: 1px solid pink;
}
td, th, caption {
padding: 10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment