kiberkun,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
div {
width: 170px;
height: 18px;
background-color: hsl(300, 100%, 27%);
margin: 5px;
}
div:after {
counter-increment: z ;
content: counter(z);
color: hsl(30, 67%, 94%);
display: block;
text-align: center;
}
body {
counter-reset: z 0;
}
td {
border: 1px solid hsl(195, 100%, 50%);
background-color: hsl(150, 100%, 50%);
}
table {
counter-reset: num 0;
border-spacing: 7px 11px;
}
tr:before {
counter-increment: num ;
content: counter(num);
color: hsl(25, 76%, 31%);
}
tr{
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function(){
[...document.querySelectorAll("tr")].reduceRight((accumulator, tr) =>{
if(document.querySelectorAll("tr").length == 9) return accumulator;
if(accumulator.querySelectorAll("div").length == 4) accumulator = tr;
else {accumulator.querySelector("td").append(tr.querySelector("div")); tr.remove()}
return accumulator
})
})
</script>
</head>
<body>
<table>
<tr id="item_1">
<td>
<div></div>
</td>
</tr>
<tr id="item_2">
<td>
<div></div>
</td>
</tr>
<tr id="item_3">
<td>
<div></div>
</td>
</tr>
<tr id="item_4">
<td>
<div></div>
</td>
</tr>
<tr id="item_5">
<td>
<div></div>
</td>
</tr>
<tr id="item_6">
<td>
<div></div>
</td>
</tr>
<tr id="item_7">
<td>
<div></div>
</td>
</tr>
<tr id="item_8">
<td>
<div></div>
</td>
</tr>
<tr id="item_9">
<td>
<div></div>
</td>
</tr>
<tr id="item_10">
<td>
<div></div>
</td>
</tr>
<tr id="item_11">
<td>
<div></div>
</td>
</tr>
<tr id="item_12">
<td>
<div></div>
</td>
</tr>
<tr id="item_13">
<td>
<div></div>
</td>
</tr>
<tr id="item_14">
<td>
<div></div>
</td>
</tr>
<tr id="item_15">
<td>
<div></div>
</td>
</tr>
<tr id="item_16">
<td>
<div></div>
</td>
</tr>
<tr id="item_17">
<td>
<div></div>
</td>
</tr>
<tr id="item_18">
<td>
<div></div>
</td>
</tr>
<tr id="item_19">
<td>
<div></div>
</td>
</tr>
<tr id="item_20">
<td>
<div></div>
</td>
</tr>
<tr id="item_21">
<td>
<div></div>
</td>
</tr>
<tr id="item_22">
<td>
<div></div>
</td>
</tr>
<tr id="item_23">
<td>
<div></div>
</td>
</tr>
<tr id="item_24">
<td>
<div></div>
</td>
</tr>
<tr id="item_25">
<td>
<div></div>
</td>
</tr>
<tr id="item_26">
<td>
<div></div>
</td>
</tr>
<tr id="item_27">
<td>
<div></div>
</td>
</tr>
<tr id="item_28">
<td>
<div></div>
</td>
</tr>
<tr id="item_29">
<td>
<div></div>
</td>
</tr>
<tr id="item_30">
<td>
<div></div>
</td>
</tr>
</table>
</body>
</html>