[javascript] Jquery insert new row into table at a certain index

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.

This question is related to javascript jquery html-table

The answer is


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.


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.


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

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

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


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.


try this:

$("table#myTable tr").last().after(data);

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?