brog
brog

Reputation: 21

Add table row after 4th element Jquery

I am trying to start a new row after each 4th element using .after() method.
My logic is to close a row tag and start a row after the fourth element. Instead of closing the row and starting a new row, a new empty row is being created.

Here is the fiddle file http://jsfiddle.net/b4xhG/1/

Jquery Code

   $("#table td:nth-child(4n)").after("</tr>  <tr>");

This is how it’s displaying

<table id="table" border="1px" width="500px">
    <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    </tr>
</table>

This is how it should display.

<table id="table" border="1px" width="500px">
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
    </tr>
        <tr>
            <td>5</td>
            <td>6</td>
            <td>7</td>
            <td>8</td>
        </tr>
        <tr>
            <td>9</td> 
        </tr>
</table>

Upvotes: 2

Views: 2768

Answers (4)

DarkAjax
DarkAjax

Reputation: 16223

Here's 2 alternative choices:

while($('#table').find('tr:last').children(':gt(3)').length > 0){
   $('#table').find('tr:last').after(
       $('#table').find('tr:last').children(':gt(3)')
           .wrapAll('<tr></tr>').parent().remove()
   );
}

Jsfiddle Demo: http://jsfiddle.net/darkajax/MFTsu/

And:

while($('#table').find('tr:last').children(':gt(3)').length > 0){
   var newRow = '';
   $('#table').find('tr:last').children(':gt(3)').each(function(i,e){
      newRow += $(e).prop('outerHTML');
   }).remove();
   $('#table').find('tr:last').after('<tr>' + newRow + '</tr>');
}

Jsfiddle Demo: http://jsfiddle.net/darkajax/YgAMd/

Upvotes: 0

Marcel Gwerder
Marcel Gwerder

Reputation: 8520

Another possible sollution (DEMO):

$('#table td:nth-child(4n)').each(function() { 
    $('<tr>').html($(this).nextAll()).appendTo('#table tbody');
});

Upvotes: 0

Ram
Ram

Reputation: 144689

var $td = $("#table td");

$td.each(function(i) {
    if (i % 4 === 0) {
        $td.slice(i, i+4).wrapAll('<tr/>');
    }
}).parent('tr').unwrap();

http://jsfiddle.net/ZyFUU/

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

You cannot insert invalid/incomplete HTML fragments (ex: "</tr><tr>") using after().

You can however do it like:

while($("#table td:nth-child(4n)").nextAll().length > 0) {
    $('<tr/>').append($("#table td:nth-child(4n)").nextAll()).appendTo('#table');    
}

Working Demo

Upvotes: 4

Related Questions