0

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

Jaqen H'ghar
  • 4,305
  • 2
  • 14
  • 26
Krishna
  • 609
  • 1
  • 6
  • 17

1 Answers1

2

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;
}

Fiddle

I hope you find the answer okay :-)

Community
  • 1
  • 1
jyrkim
  • 2,849
  • 1
  • 24
  • 33
  • Thanks Bro, let me check, Hope this will do... :) – Krishna Apr 06 '15 at 12:02
  • Yes Bro, the logic/code u suggested resolved my problem :) . But I did some changes in suggested code like, `$(".location td").each(function (index) { if ((index % 2) == 0) { $(".location tbody").append($('')); } $(".location tr").last().append($(this)); });` mainly I changed the **if** condition and removed code for removing first row..... Thanks alot, for neatly explained solution – Krishna Apr 06 '15 at 12:32