You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为DataTables生成的THEAD添加thead-dark类?

Solution: Add Bootstrap 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:

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:

  • initComplete is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:47:37