-1

I have a table with its tr tags. I want to display two tr tags side by side by its class. How can i able to do that using jquery.

<table>
   <tr class='1'>
     <td>First</td>
   </tr>
   <tr class='1'>
      <td>second</td>
   </tr>
   <tr class='2'>
       <td>third</td>
   </tr>
   <tr class='3'>
       <td>fourth</td>
   </tr>
   <tr class='3'>
       <td>fifth</td>
   </tr>  
</table>

Then in the output i want to display

 First     Second
 Third
 Fourth    Fifth

I want to set those dynamically how can i do that using jquery or javascript. I want to use the class declared for the tr tag. I know want to use <td> tag for that. Any help is appreciated

Pa1
  • 630
  • 4
  • 11
  • 21

2 Answers2

1

Here's the first way that came to mind:

var $tds = $("td");      // get all the tds
[].reverse.call($tds);   // reverse the order so we can easily loop backwards

$tds.each(function() {
    var $parentRow = $(this).parent(),
        // find the first row with the same class that isn't this row
        $firstTrSameClass = $("tr").filter("." +$parentRow.attr("class"))
                                   .not($parentRow).first();
    if ($firstTrSameClass.length > 0) { // if there is such a row
        $firstTrSameClass.append(this); // move the td
        $parentRow.remove();            // delete the original row
    }   
});

Demo: http://jsfiddle.net/pgcdq/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

I can't really see a use case here but I guess the eaisiest would be to create new rows and move cells to them. You will find information on moving elements here: How to move an element into another element?

Community
  • 1
  • 1
Nux
  • 9,276
  • 5
  • 59
  • 72