How to add class to tr using jQuery datatable

By FoxLearn 5/16/2024 8:18:45 AM   88
This post shows you how to add a class name to jquery.datatables

datatables add class to tr

To add a class to a <tr> element in a jQuery DataTable, you can use the createRow option.

Here's an example of how you can achieve this:

For example:

$('#table').dataTable( {
  "createdRow": function( row, data, dataIndex ) {
      // Add your condition here to determine when to add the class

$('tr', row) will search for a tr element inside the row provided as context parameter. If you want to add a class to row with conditionally based on the row's data you can do as shown below.

$('#table').dataTable( {
  "createdRow": function(row, data, dataIndex ) {
    if (data[4] == "X" ) {
      $(row).addClass('text-95 text-secondary');
} );

In this example:

#table is the ID of your DataTable.

createdRow is a function that will be called for each row in the DataTable.

Inside the createdRow function, you can add your condition to determine when to add the class to the row.

If the condition is met, you can use $(row).addClass('your-class-name') to add your desired class to the row.