'How to create set attribute to a table header when creating the table in JavaScriipt
I am trying to set a class attribute to a table head for proper styling in JavaScript.
I have succeeded in creating the Table Headers but could not set the class attributes so that the styling in the CSS file can be applied.
The 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 works well, except the Classes are not attaching.
Solution 1:[1]
You think too complicated. Just add the class name to your element using classlist.add
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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thallius |
