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

1 Answer 1

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 :-)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Bro, let me check, Hope this will do... :)
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($('<tr>')); } $(".location tr").last().append($(this)); }); mainly I changed the if condition and removed code for removing first row..... Thanks alot, for neatly explained solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.