如何在 JavaScript 中创建 table 时将属性设置为 table header

How to create set attribute to a table header when creating the table in JavaScriipt

我正在尝试将 class 属性设置为 table head 以便在 JavaScript 中设置正确的样式。 我已成功创建 Table Headers,但无法设置 class 属性,因此无法应用 CSS 文件中的样式。

JavaScript

// Create Classes for the table head styling
let tableSN = document.createAttribute("class");
let tableModel = document.createAttribute("class");
let tableDesc = document.createAttribute("class");
let tableQty = document.createAttribute("class");
let tableUnit = document.createAttribute("class");
let tableTotal = document.createAttribute("class");

// Set names to the Classes
tableSN.value= "sn";
tableModel.value = "model";
tableDesc.value = "desc";
tableQty.value = "qty";
tableUnit.value = "unit";
tableTotal.value = "total";


// Create Table Headings  and Classes List
let headers = ['SN', 'MODEL', 'DESCRIPTION', 'PRICE', 'QTY', 'AMOUNT'];
let myClasses = [tableSN, tableModel, tableDesc, tableQty, tableUnit, tableTotal];

// Select the DIV table container
let tableContainer = document.querySelector('#table');

// Create the table elements
let table = document.createElement('table');
let headerContainer = document.createElement('thead');
let headerRow = document.createElement('tr');

//Create the table headers
headers.forEach(headerText => {
   let header = document.createElement('th');
          
   // This is my problem. I want to attach each `class` to each table `head` created.
   for(let i=0; i < myClasses.length; i++ ) {
          header.setAttribute = myClasses[i];
   }

   let textNode = document.createTextNode(headerText);
          
   header.appendChild(textNode);
   headerRow.appendChild(header);
});

headerContainer.appendChild(headerRow);
table.appendChild(headerContainer);

Table 效果很好,除了 类 没有附加。

你想的太复杂了。只需使用 classlist.add

将 class 名称添加到您的元素
const myClasses = ["className1", "className2"];

headers.forEach(headerText => {
   let header = document.createElement('th');
   myClasses.forEach(className => header.classList.add(className));
   let textNode = document.createTextNode(headerText);          
   header.appendChild(textNode);
   headerRow.appendChild(header);
});