How do I add a class to THEAD created by datatables?

Viewed 1564

I am creating a datatable using javascript. The application itself uses bootstrap and all tables are currently styled by adding the "thead-dark" class to . However datatables does not add this class when generating using sourced data. I went through datatables documentation but could not find a solution already builtin. So I went to google and tried a few different things, but no success. I am skilled with PHP but I do not have much experience with Javascript. And since this table is to be used as a document manager, PHP is not very well suited for this job. Because I would need to reload the page all the time.

Thanks for your help!

HTML:

<div class="tab-pane" id="documents">
    <div class="table-responsive">
        <table id="documents_tbl" class="table table-hover table-striped table-bordered dt-responsive" style="width:100%"></table>
    </div>
</div>

JAVASCRIPT:

<script>
    var dataSet = [
      [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ],
      [ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750" ],
      [ "Shou Itou", "Regional Marketing", "Tokyo", "8899", "2011/08/14", "$163,000" ],
      [ "Michelle House", "Integration Specialist", "Sydney", "2769", "2011/06/02", "$95,400" ],
      [ "Suki Burks", "Developer", "London", "6832", "2009/10/22", "$114,500" ],
      [ "Prescott Bartlett", "Technical Author", "London", "3606", "2011/05/07", "$145,000" ],
      [ "Gavin Cortez", "Team Leader", "San Francisco", "2860", "2008/10/26", "$235,500" ],
      [ "Martena Mccray", "Post-Sales support", "Edinburgh", "8240", "2011/03/09", "$324,050" ],
      [ "Unity Butler", "Marketing Designer", "San Francisco", "5384", "2009/12/09", "$85,675" ]
    ];
    $(document).ready(function() {
      $('#documents_tbl').DataTable({
        data: dataSet,
        columns: [
          { title: "Name" },
          { title: "Position" },
          { title: "Office" },
          { title: "Extn." },
          { title: "Start date" },
          { title: "Salary" }
        ]
      });
    });
</script>
2 Answers

I suppose you just want to add a class to a table after datatables has rendered.

You can just call this after the datatable call:

$('#documents_tbl thead').addClass('thead-dark');

Don't forget if you added the stylesheet of Datatables, some things could interfere with this.

You can add the class after the table is initialized.

$('#documents_tbl_wrapper thead tr th').each(function () { $(this).addClass('thead-dark') })
Related