fnAddTr

Add a tr element to the table

  • Author: Allan Jardine
  • Deprecated: This plug-in has been deprecated and replaced with other functionality. Please see the detailed description below for more information.

This method will add an existing tr element to a DataTable. This can be useful for maintaining custom classes and other attributes which have been explicitly assigned to the row.

DataTables 1.10+ has row.add() and rows.add() which have this ability built in, and extend it to be able to use jQuery objects as well as plain tr elements. As such this method is marked deprecated, but is available for use with legacy version of DataTables. Please use the new API if you are used DataTables 1.10 or newer.

Plug-in code

jQuery.fn.dataTableExt.oApi.fnAddTr = function ( oSettings, nTr, bRedraw ) {
    if ( typeof bRedraw == 'undefined' )
    {
        bRedraw = true;
    }

    var nTds = nTr.getElementsByTagName('td');
    if ( nTds.length != oSettings.aoColumns.length )
    {
        alert( 'Warning: not adding new TR - columns and TD elements must match' );
        return;
    }

    var aData = [];
    var aInvisible = [];
    var i;
    for ( i=0 ; i<nTds.length ; i++ )
    {
        aData.push( nTds[i].innerHTML );
        if (!oSettings.aoColumns[i].bVisible)
        {
            aInvisible.push( i );
        }
    }

    /* Add the data and then replace DataTable's generated TR with ours */
    var iIndex = this.oApi._fnAddData( oSettings, aData );
    nTr._DT_RowIndex = iIndex;
    oSettings.aoData[ iIndex ].nTr = nTr;

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

    // Hidding invisible columns
    for ( i = (aInvisible.length - 1) ; i >= 0 ; i-- )
    {
        oSettings.aoData[iIndex]._anHidden[ i ] = nTds[aInvisible[i]];
        nTr.removeChild( nTds[aInvisible[i]] );
    }

    // Redraw
    if ( bRedraw )
    {
        this.oApi._fnReDraw( oSettings );
    }
};

CDN

This plug-in is available on the DataTables CDN:

JS

Note that if you are using multiple plug-ins, it is beneficial in terms of performance to combine the plug-ins into a single file and host it on your own server, rather than making multiple requests to the DataTables CDN.

Version control

If you have any ideas for how this plug-in can be improved, or spot anything that is in error, it is available on GitHub and pull requests are very welcome!

Example

var table = $('#example').dataTable();
  table.fnAddTr( $('<tr>'+
       '<td>1</td>'+
       '<td>2</td>'+
       '<td>3</td>'+
    '</tr>')[0]
  );