DataTables: Add class to table cells, but not table headers?

16,167

Solution 1

Thanks to mainguy and markpsmith for posting their answers. I'll throw my own solution into the mix, but I'd still like to see what everyone thinks the best performing solution would be:

$('#qpidvulh_to-do_list thead th').removeClass('editable');

Solution 2

Use this to add the class to the cell, 100% working solution, make sure the you give the correct target number while adding the class, here createdCell function adds class to the targeted cell,

var oTable  = $('#<?php echo $module; ?>').DataTable({
                  columnDefs: [{"orderable": true, "targets": 1,
                        'createdCell':  function (td, cellData, rowData, row, col) {
                           $(td).addClass('myclass');
                           // $(td).parent('tr').attr('data-id', rowData[0]); // adds the data attribute to the parent this cell row
                        }
                  }]
    });

Solution 3

I had this problem but the suggested solution didn't really work for me because I am applying different types of inputs (number, text) selectively to cells in multiple tables. I have an onclick event for the cell to convert it into an editable box. I changed where it is called from

table.on('click', '.edit-text', function() {
    // yadda yadda;
}

to

table.on('click', 'td.edit-text', function() {
    // yadda yadda;
}

In this way the function ignores the 'th' cells with that class.

EDIT:
A second way I have found is to use the createdCell option in the columns definition:

columns: [
    {
        data: 'property_name',
        createdCell: cell => $(cell).addClass('some-class')
    }
]
Share:
16,167
eclipsis
Author by

eclipsis

Updated on June 19, 2022

Comments

  • eclipsis
    eclipsis almost 2 years

    I'm using the following code to initialize jQuery DataTables:

    var oTable = $('#qpidvulh_to-do_list').dataTable( {
        "columns": [
            {
                "data": "item",
                "className": "editable"
            }
        ]
    } )
    

    The issue with this code is that it adds the editable class to the th of each column, even though I only want it added to the td of each column.

    How can I get the code to only add the editable class to the cells of each column and not their headers?

  • nonzaprej
    nonzaprej over 5 years
    This unfortunately adds the classes to both the cells and the headers.