fnGetColumnIndex

Get the column index by searching the column titles

Maintenance of web-sites can often cause unexpected headaches, particularly if the hardcoded index of an array (the columns in a DataTables instance) needs to change due to an added or removed column. This plug-in function will match a given string to the title of a column in the table and return the column index, helping to overcome this problem.

Plug-in code

jQuery.fn.dataTableExt.oApi.fnGetColumnIndex = function ( oSettings, sCol )
{
    var cols = oSettings.aoColumns;
    for ( var x=0, xLen=cols.length ; x<xLen ; x++ )
    {
        if ( cols[x].sTitle.toLowerCase() == sCol.toLowerCase() )
        {
            return x;
        }
    }
    return -1;
};

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.fnGetColumnIndex( 'Browser' );