I have successfully retrieved JSON data and programmatically added them to a table. However, I am facing an issue with adding the table headers programmatically. You can run the code below to see it in action. If you want to test it out, feel free to do so by clicking on this running LINK Codepen Code
function search() {
var queryURL = "https://jsonplaceholder.typicode.com/users";
fetch(queryURL)
.then(response=> response.json())
.then(data=>displayUsersAsATable(data))
.catch(function (error) {
console.log('Error during fetch: ' + error.message);
});
}
function displayUsersAsATable(data) {
var usersDiv = document.querySelector("#users");
usersDiv.innerHTML = "";
// creates and populate the table with users
var table = document.createElement("table");
data.forEach(function (currentUser) {
var myhead = table.createTHead();
myhead.innerHTML = "Table Heading"
var mycaption = table.createCaption();
mycaption.innerHTML = "Table Caption"
var row = table.insertRow();
var nameCell = row.insertCell();
nameCell.innerHTML = currentUser.email;
var cityCell = row.insertCell();
cityCell.innerHTML = currentUser.address.city;
});
// adds the table to the div
usersDiv.appendChild(table);
}