Reputation: 659
I have a table like this,
<table class='location'>
<tbody>
<tr align=center>
<td>Content 1</td>
<td>Content 2</td>
<td>Content 3</td>
<td>Content 4</td>
<td>Content 5</td>
<td>Content 6</td>
<td>Content 7</td>
<td>Content 8</td>
</tr>
</tbody>
</table>
I want to re-arrange this table using JQuery like,
<table class='location'>
<tbody>
<tr align=center>
<td>Content 1</td>
<td>Content 2</td>
</tr>
<tr align=center>
<td>Content 3</td>
<td>Content 4</td>
</tr>
<tr align=center>
<td>Content 5</td>
<td>Content 6</td>
</tr>
<tr align=center>
<td>Content 7</td>
<td>Content 8</td>
</tr>
</tbody>
</table>
2 cells in each row. ie 4 rows with 2 cells each.
Please guide me, as I am beginner to JQuery.
Thanks
Upvotes: 0
Views: 1962
Reputation: 2869
Below several jQuery methods such as each(), append(), attr(), first() and last() are applied. Also isOdd function from an older Stackoverflow answer is being used to check td
element position.
// loop through each table td element
$("table.location td").each(function (index) {
// check if it's odd or even td element based on its position
// element index is added 1 before checking if its position has even or odd number because index starts from 0
var odd = isOdd((index + 1));
//if td element is position order number is odd then create new table row
//and append it to the table
if (odd) {
$("table.location tbody").append($("<tr>").attr("align", "center"));
}
//then append the current td element to the last table row
//the last table row is the most recently created row
$("table.location tr").last().append($(this));
});
//finally remove the first table row which is empty
$("table.location tr").first().remove();
function isOdd(num) {
return num % 2;
}
I hope you find the answer okay :-)
Upvotes: 2