Giving custom classes to each TD for styling - Datatables & jQuery

JavascriptJqueryDatatablesHtml Table

Javascript Problem Overview


I'm using datatables for displaying server-side data in tables.

I can't target and style individual cells (<TD>) though. I search a bit and found it might be possible with:

"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
    ....
}

... but I'm not quite sure how because I have a few table and not all have the same number of columns and rows. I want to give common class to all TDs of a 'column'.

Javascript Solutions


Solution 1 - Javascript

You can use sClass parameter in Columns definition. For example, if you have 3 columns and want to pass custom class for second and third column, you can:

"aoColumns": [
    null,
    { "sWidth": "95px", "sClass": "datatables_action" },
    { "sWidth": "45px", "sClass": "datatables_action" }
]

You can check datatables documentation

Solution 2 - Javascript

You can use columnDefs to define classes for each column.

Example in coffeescript:

$('table').dataTable(
  columnDefs: [
    {
      targets: -1 # targets last column, use 0 for first column
      className: 'last-column'
    }
  ]
);

This is using new API 1.10+.

Solution 3 - Javascript

For those who found this question when searching for fnRowCallback and want to add styling based on cell content rather than using static css classes, using the fnRowCallback will do the trick:

oTable = $('#matrix').dataTable({
  ...
  "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
    for (var i in aData)  {

      // Check if a cell contains data in the following format:
      // '[state] content'
      if (aData[i].substring(0,1)=='[') {

        // remove the state part from the content and use the given state as CSS class
        var stateName= aData[i].substring(1,aData[i].indexOf(']'));
        var content= aData[i].substring(aData[i].indexOf(']')+1);
        $('td:eq('+i+')', nRow).html(content).addClass(stateName);
      }
    }
  }
});

Hope this may be useful for some future visitor :-)

Solution 4 - Javascript

Here's how to do it using createdCell, using DataTables 1.10+ syntax. The benefit of this approach is that you can conditionally style the cells.

"columnDefs": [
{
		"targets": [16],
		"createdCell": function(td, cellData, rowData, row, col) {
			switch(cellData) {
			case "Pending":
				$(td).addClass('pending');
				break;
			case "Rejected":
				$(td).addClass('rejected');
				break;
			case "Approved":
				$(td).addClass('approved');
				break;
			case "SAP":
				$(td).addClass('sap');
				break;
			case "Reconciled":
				$(td).addClass('reconciled');
				break;
			}
		}
	}
],

Solution 5 - Javascript

If you want to target the row or an individual cell in a callback:

var table = $('#order-history-table').DataTable(
    {
        "ajax": url,
        "pageLength": 20,
        "createdRow": function( row, data, dataIndex ) {
        
            // Add a class to the cell in the second column
            $(row).children(':nth-child(2)').addClass('text-justify');

            // Add a class to the row
            $(row).addClass('important');
        }
    }
);

I was unable to get the 'createdCells' parameter to work so had to do it through the row.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneozzyView Question on Stackoverflow
Solution 1 - JavascriptLukasz KoziaraView Answer on Stackoverflow
Solution 2 - JavascriptjmarceliView Answer on Stackoverflow
Solution 3 - JavascriptSaschaM78View Answer on Stackoverflow
Solution 4 - Javascriptdevlin carnateView Answer on Stackoverflow
Solution 5 - JavascriptomarjebariView Answer on Stackoverflow