DataTables - Loop through columns/header and set width

Viewed 885

I want to loop through columns on datatable. Check the class of the header and set the width of the column.

As per DataTables docs. This is how you loop through the header but how can I set the column width?

<table id="data-table">
    <thead>
        <tr>
            <th>ID</th>
            <?php if ($client) : ?>
            <th class="client">Client</th>
            <?php endif; ?>
            <th>Product</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><?php echo $id; ?></td>
            <?php if ($client) : ?>
            <td><?php echo $client; ?></td>
            <?php endif; ?>
            <td><?php echo $product; ?></td>
        </tr>
    </tbody>
</table>

<script>
  var myTable = $('#data-table').DataTable();
  myTable.columns().header().each(function(value, index){
    if ( $(value).hasClass('client') ) {
       // Set column width here
    }
  })
</script>

2 Answers

Hate to say it, but I dont think the answer above would ever do the trick. First of all you should target columns(), not columns; second setting a width on <th> elements does not change the browsers internal table calculation, but defining a min-width does. Also use chaining to be sure that columns() are looped after the DataTable is instantiated :

const table = $('#data-table').DataTable({
}).columns().header().each(function(th) {
  if ( $(th).hasClass('client') ) {
    $(th).css('min-width', '200px') 
  }
})

http://jsfiddle.net/wvtmq5d7/

I think you can easily do it using CSS only like:

.client { width: 100px; }

But in case you need to do some manipulation in JS to set the width, then you can do it like:

var myTable = $('#data-table').DataTable();
myTable.columns.header().each(function(column, index) {
  if ($(column).hasClass('client')) {
    // Set column width here
    $(column).width(100)
    
    //Or
    // $(column).css("width", 100);
  }
})

Please note, if no explicit unit is specified (like "em" or "%") then "px" is assumed. So in the example, it is 100px actually. You can update it as per your requirement.

Related