121

I know how to append or prepend a new row into a table using jquery:

$('#my_table > tbody:last').append(html);

How to I insert the row (given in the html variable) into a specific "row index" i. So if i=3, for instance, the row will be inserted as the 4th row in the table.

Augustus
  • 1,479
  • 2
  • 17
  • 31
aeq
  • 10,377
  • 15
  • 45
  • 46

10 Answers10

165

You can use .eq() and .after() like this:

$('#my_table > tbody > tr').eq(i-1).after(html);

The indexes are 0 based, so to be the 4th row, you need i-1, since .eq(3) would be the 4th row, you need to go back to the 3rd row (2) and insert .after() that.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 8
    It should be noticed that if jQuery's eq function is given a negative value, it'll loop around to the end of the table. So running this and trying to insert it on the 0 index will cause the new row to be inserted at the end – rossisdead Dec 22 '11 at 14:23
  • 2
    And add `.before(html)` if you want to insert it before that index – Abhinav Dec 17 '13 at 04:30
  • 1
    this fails, if there are no rows in the table, does anyone have a solution(index based) which works even for the first row? – MartinM Apr 29 '14 at 13:20
  • @MartinM if you're inserting *even if there are no rows*, then that's a totally different scenario (where the index doesn't matter?) - do you want to append to the end no matter what? – Nick Craver Apr 29 '14 at 13:23
  • @NickCraver, no I'm just looking for a general index based solution(like this), but my table is empty at the beggining..I can, of course check, if the table is empty and insert first row and then continue with your method, but this seems not ellegant to me.. – MartinM Apr 29 '14 at 13:25
  • @MartinM you can save the first bit and `.length` check...but since 0 would wrap around, can't you just if/else the `i === 0` case and `.append()` to the tbody in the `0` case? – Nick Craver Apr 29 '14 at 13:28
  • @NickCraver yes of course, I was just curious, if there's an elegant way without if/else, thank you – MartinM Apr 29 '14 at 13:31
  • @MartinM I can't think of a more elegant solution at the moment - it's 2 different hierarchy levels which either makes it ugly, or fairly inefficient - I'd personally go if/else there, happy to help! – Nick Craver Apr 29 '14 at 13:33
19

Try this:

var i = 3;

$('#my_table > tbody > tr:eq(' + i + ')').after(html);

or this:

var i = 3;

$('#my_table > tbody > tr').eq( i ).after(html);

or this:

var i = 4;

$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);

All of these will place the row in the same position. nth-child uses a 1 based index.

user113716
  • 318,772
  • 63
  • 451
  • 440
4

I know it's coming late but for those people who want to implement it purely using the JavaScript , here's how you can do it:

  1. Get the reference to the current tr which is clicked.
  2. Make a new tr DOM element.
  3. Add it to the referred tr parent node.

HTML:

<table>
     <tr>
                    <td>
                        <button id="0" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>

     <tr>
                    <td>
                        <button id="1" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>
     <tr>
                    <td>
                        <button id="2" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>

In JavaScript:

function addRow() {
        var evt = event.srcElement.id;
        var btn_clicked = document.getElementById(evt);
        var tr_referred = btn_clicked.parentNode.parentNode;
        var td = document.createElement('td');
        td.innerHTML = 'abc';
        var tr = document.createElement('tr');
        tr.appendChild(td);
        tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
        return tr;
    }

This will add the new table row exactly below the row on which the button is clicked.

Prateek
  • 1,065
  • 8
  • 6
4

Note:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
2

try this:

$("table#myTable tr").last().after(data);
Agus Puryanto
  • 1,355
  • 4
  • 16
  • 15
1

Use the eq selector to selct the nth row (0-based) and add your row after it using after, so:

$('#my_table > tbody:last tr:eq(2)').after(html);

where html is a tr

Adam
  • 43,763
  • 16
  • 104
  • 144
1
$('#my_table tbody tr:nth-child(' + i + ')').after(html);
Arjan
  • 19,957
  • 2
  • 55
  • 48
0

Adding on to Nick Craver's answer and also considering the point raised by rossisdead, if scenario exists like one has to append to an empty table, or before a certain row, I have done like this:

var arr = []; //array
if (your condition) {
  arr.push(row.id); //push row's id for eg: to the array
  idx = arr.sort().indexOf(row.id);

  if (idx === 0) {   
    if (arr.length === 1) {  //if array size is only 1 (currently pushed item)
        $("#tableID").append(row);
    }
    else {       //if array size more than 1, but index still 0, meaning inserted row must be the first row
       $("#tableID tr").eq(idx + 1).before(row);
    }   
  }          
  else {     //if index is greater than 0, meaning inserted row to be after specified index row
      $("#tableID tr").eq(idx).after(row);
  }    
}

Hope it helps someone.

Jaggan_j
  • 488
  • 1
  • 8
  • 9
0

To add the right under a specific node(data-tt-id), this worked for me:

var someValue = "blah-id";

$("#tableID > tbody > tr[data-tt-id="' + someValue + '"]').after(row);
z atef
  • 7,138
  • 3
  • 55
  • 50
-1
$($('#my_table > tbody:last')[index]).append(html);
Eli Grey
  • 35,104
  • 14
  • 75
  • 93