如何为DataTables生成的THEAD添加thead-dark类?
thead-dark to DataTables-generated Tables Hey there! I get that you're trying to apply Bootstrap's thead-dark class to your dynamically generated DataTables table—since DataTables doesn't add this class automatically when building the table from a dataset. Let's fix this with a couple of straightforward JavaScript approaches that even someone with limited JS experience can follow:
Method 1: Use DataTables' initComplete Callback (Recommended)
This is the most reliable way because it runs only after DataTables has fully initialized and built the table. We'll use DataTables' built-in hook to target the <thead> and add the class:
$(document).ready(function() { $('#documents_tbl').DataTable({ data: dataSet, columns: [ { title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Extn." }, { title: "Start date" }, { title: "Salary" } ], // This function runs once the table is fully initialized initComplete: function(settings, json) { // Target the table's thead element and add the Bootstrap class $(this.api().table().header()).addClass('thead-dark'); } }); });
How it works:
initCompleteis a DataTables callback that triggers after all table elements (including the dynamically created<thead>) are rendered.this.api()gives us access to the DataTables API, which lets us safely target the table's header without relying on generic selectors..addClass('thead-dark')applies Bootstrap's dark header styling to the<thead>.
Method 2: Direct DOM Manipulation (Simple & Quick)
If you prefer a more straightforward approach, you can directly target the <thead> right after initializing DataTables:
$(document).ready(function() { // Initialize the DataTable first var table = $('#documents_tbl').DataTable({ data: dataSet, columns: [ { title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Extn." }, { title: "Start date" }, { title: "Salary" } ] }); // Add the Bootstrap class to the thead once the table is ready $('#documents_tbl thead').addClass('thead-dark'); });
How it works:
- After DataTables finishes building the table, we use a basic jQuery selector (
$('#documents_tbl thead')) to find the dynamically created<thead>element. .addClass('thead-dark')applies the Bootstrap styling just like you would with a static table.
Either method will give you the dark header style you want for your document manager table, without needing to rely on PHP and page refreshes.
内容的提问来源于stack exchange,提问作者L. Ouellet

