If you're looking for a simple way to rearrange cells in a table by moving each cell in front of the previous one, here's a basic method that can help you achieve that.
While there may be more elegant or concise methods to accomplish this task, understanding the fundamentals is always valuable for mastering advanced techniques.
Here's a breakdown of the process:
$("table>thead>tr,table>tbody>tr").each
This snippet loops through both the header (thead) and body (tbody) sections of the table. Alternatively, you could use $("table tr")
, but this might not work correctly with nested tables.
$(this).find("th,td").eq(2).each(
In this line, this
refers to the current row (tr
) from the previous loop iteration. It looks for child elements th
and td
, selecting only the third column (zero-based index).
$(this).insertBefore($(this).prev());
Now, this
represents the selected th/td element from the previous loop. It takes the third column cell and moves it in front of the preceding cell.
Check out the code snippet below for a visual representation:
$("button").click(() =>
$("table>thead>tr,table>tbody>tr").each(function() {
$(this).find("th,td").eq(2).each(function() {
$(this).insertBefore($(this).prev());
});
})
);
table, th, td {
border: 1px solid #CCC;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>cell 1 1</td>
<td>cell 1 2</td>
<td>cell 1 3</td>
</tr>
<tr>
<td>cell 2 1</td>
<td>cell 2 2</td>
<td>cell 2 3</td>
</tr>
</tbody>
</table>
<button type='button' id='clickme'>click me</button>