Copying Classes from <col> to corresponding <td>
Title says it all
by Gust van de Wal
HTML
<table>
<colgroup>
<col class="foo1" />
<col class="bar1" />
<col class="baz1" />
<col class="foo2" />
<col class="bar2" />
<col class="baz2" />
<col />
</colgroup>
<tr>
<th><span>A</span></th>
<th><span>B</span></th>
<th><span>C</span></th>
<th><span>D</span></th>
<th><span>E</span></th>
<th><span>F</span></th>
</tr>
<tr>
<td colspan="2"><span>a</span><span>b</span></td>
<td><span>c</span></td>
<td><span>d</span></td>
<td><span>e</span></td>
<td><span>f</span></td>
</tr>
<tr>
<td><span>a</span></td>
<td colspan="2"><span>b</span><span>c</span></td>
<td><span>d</span></td>
<td><span>e</span></td>
<td><span>f</span></td>
</tr>
<tr>
<td colspan="2"><span>a</span><span>b</span></td>
<td colspan="2"><span>c</span><span>d</span></td>
<td><span>e</span></td>
<td><span>f</span></td>
</tr>
<tr>
<td colspan="2"><span>a</span><span>b</span></td>
<td><span>c</span></td>
<td colspan="2"><span>d</span><span>e</span></td>
<td><span>f</span></td>
</tr>
<tr>
<td><span>a</span></td>
<td><span>b</span></td>
<td><span>c</span></td>
<td><span>d</span></td>
<td colspan="2"><span>e</span><span>f</span></td>
</tr>
</table>
CSS
.foo1{background-color:#FBB}
.bar1{background-color:#FFB}
.baz1{background-color:#BFB}
.foo2{background-color:#BFF}
.bar2{background-color:#BBF}
.baz2{background-color:#FBF}
*{box-sizing:border-box;position:relative}html,body{height:100%;overflow:hidden}body{margin:0;display:flex;justify-content:center;align-items:center}table{border-collapse:collapse;text-align:center}th,td{padding:0}th{font-weight:normal}span{display:block;float:left;width:70px;padding:.3em}span:nth-child(n+2)::before{content:'&';position:absolute;top:0;left:0;bottom:0;padding:inherit;transform:translateX(-50%)}
JavaScript
$(function () {
$('colgroup').each(function () {
var $colgroup = $(this)
var classes = $colgroup.children().map(function () { return $(this).attr('class') })
$colgroup.siblings().children('tr').each(function () {
var col = 0
$(this).children().each(function () {
var $child = $(this)
$child.addClass(classes[col])
col += parseInt($child.attr('colspan')) || 1
})
})
$colgroup.remove()
})
})