I'm having trouble creating a header row for a DIV table using JavaScript (without jQuery). Instead of getting the expected output, I'm getting a row with the array items as headings separated by commas.
https://i.sstatic.net/8O5QR.png
var main = document.getElementById("left");
var likertTable = document.createElement("DIV"); //main table div
likertTable.setAttribute("class", "divTable");
var tableHeading = document.createElement("DIV"); // table heading
tableHeading.setAttribute("class", "divTableHeading");
var row = document.createElement("DIV");
row.setAttribute("class", "divTableRow");
tableHeading.appendChild(row);
likertTable.appendChild(tableHeading);
main.appendChild(likertTable);
var tableHeader = ["Question", "Strongly Agree", "Agree", "Undecided", "Disagree", "Strongly Disagree"];
for (var i = 0; i < tableHeader.length; i++) {
var tableCell = document.createElement("DIV");
tableCell.setAttribute("class","divTableCell");
row.appendChild(tableCell);
tableCell.innerHTML = tableHeader[i];
}
.divTable{
display: table;
width: 100%;
}
.divTableRow {
display: table-row;
}
/*.divTableHeading {
background-color: #EEE;
display: table-header-group;
}*/
.divTableCell, .divTableHead {
border: 1px solid #999999;
display: table-cell;
padding: 3px 10px;
}
.divTableHeading {
background-color: #EEE;
display: table-header-group;
font-weight: bold;
}
.divTableFoot {
background-color: #EEE;
display: table-footer-group;
font-weight: bold;
}
.divTableBody {
display: table-row-group;
}
<div id="left"></div>
The variable should be var tableHeader = ranges;
instead of var tableHeader = [ranges];
. This mistake caused the issue in generating the correct output.
After realizing the error, everything worked perfectly when I tested the script in the snippets editor.
Grateful for the help from the community on StackOverflow.