Programmatically insert headers to a table

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);
    } 

Answer №1

According to this source, the table API method insertCell cannot be used to insert <th> tags in HTML. However, this can be achieved programmatically by creating the element using document.createElement and then inserting it.

In the code snippet provided, the creation of table headers is within a loop which could result in multiple headers being created for each piece of data. To address this, I have placed the header creation outside the loop assuming this was the intended behavior.

Here is a related code excerpt:

var myhead = table.createTHead();
var headRow = myhead.insertRow();
var emailHead = document.createElement('th');
var nameHead = emailHead.cloneNode();
headRow.appendChild(emailHead);
headRow.appendChild(nameHead);
emailHead.innerHTML = 'Email';
nameHead.innerHTML = 'Name';

Check out a working demo below:

function search() {
var queryURL = "https://jsonplaceholder.typicode.com/users";

fetch(queryURL)
            .then(response=> response.json())
             //arrow function by Mauro - works fine!
            .then(data=>displayUsersAsATable(data))
               .catch(function (error) {
                console.log('Error during fetch: ' + error.message);
            });
}

//questa è una variazione

function displayUsersAsATable(data) {
// users is a JavaScript object

// empty the div that contains the results
var usersDiv = document.querySelector("#users");
usersDiv.innerHTML = "";

// create and populate the table with users
var table = document.createElement("table");
var mycaption = table.createCaption();
mycaption.innerHTML = "Table Caption"

//Creating and populating table header.
var myhead = table.createTHead();
var headRow = myhead.insertRow();
var emailHead = document.createElement('th');
var nameHead = emailHead.cloneNode();
headRow.appendChild(emailHead);
headRow.appendChild(nameHead);
emailHead.innerHTML = 'Email';
nameHead.innerHTML = 'Name';

var tableBody = table.createTBody();

// iterate on the array of users
data.forEach(function (currentUser) {
//inserimento dei titoli della colonna programmaticamente
   // creates a row
   var row = tableBody.insertRow();
   // insert cells in the row
   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);
} 
table {
  margin-top: 20px;
}
table, tr, td {
  border: 1px solid;
background-color: rgb(200, 200, 100);
} 
<head>
<title>Working with remote data</title>
  <meta charset="utf-8"/>
  <!-- Polyfill in case your browser does not support the fetch API -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/0.10.1/fetch.js"></script>

</head>
<body>
  <button onclick="search();">Get remote list of users' names and emails using the fetch API</button>
  <div id="users"></div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with React's complex nested components not functioning properly

I am new to using React and have been searching for an explanation without success. Most examples I found were with basic components that do not match what I need. My goal was to create a Single Page Application (SPA) with React, following this basic wire ...

What offers better performance: XmlHttpRequest response in HTML or JSON format?

When it comes to a highly AJAX-enabled website, the content of the web page can be updated partially using AJAX. This basically involves changing HTML tags or parts of the web page. So, when faced with this situation, we must decide between two approaches ...

Populate an HTML table with the days of the month and corresponding dates retrieved from a PostgreSQL database using JavaScript

I'm struggling to figure out how to use generate_series to populate an HTML table where the 'key' of <tr> corresponds to the days of the selected month and year using an <input type='month'>. So far, with the help I re ...

Ajax cannot seem to come to a resolution

After completing my learning on Ajax, I decided to work on a simple project - a port scanner. However, I am facing issues with it as it is not working properly. The only message that pops up is 'Scan started' and I can't figure out what the ...

Styling Material UI height in select elements (React)

Currently, I am developing a react application that utilizes Material Dashboard. I am encountering an issue with the height of a Select (drop-down list) component. See image here On the right side of my app, there is a standard input field and I would li ...

Issue with radio button click event not triggering

Whenever I click on a radio button, I want to call a function, but for some reason, it's not working as expected. I found this fiddle that demonstrates exactly what I want, but when I implement it in my code, it doesn't work. Here's a snipp ...

Delete a specific element based on its class by utilizing the parent() method

As I modify a jQuery validator, it adds a div to the parent element when an error occurs. My goal is to remove this inserted div with a specific class name from the parent. $(element).parent().remove('.removeThis'); Although I expected the code ...

A guide on cycling through partitions in SQL, selectively gathering rows from a designated week, and generating a fresh table containing the captured data

My data is organized in partitions based on the year, month, and day of record receipt by servers. The dataset includes columns for event timestamps and server timestamps. To collect rows corresponding to events occurring between Jan 18, 2021, and Jan 24, ...

AngularJS: Implementing a toggle click function for a list of items within an iframe

Here's the workflow I'm dealing with: I have a collection of items, each having an ng-click event that triggers the display of an iframe below the clicked item. The process works like this: When clicking an item, a hidden div tag beneath it ap ...

Step-by-step guide on populating input fields with JSON data for each row

As a beginner in Programming, I have been searching for an answer to the following problem on this site for days but haven't been able to figure it out yet. To explain briefly, there will be an input form where the user can define the number of rows ...

Passing the v-model property from a child component to a parent in VueJS

Consider a scenario where there is a Vue component structured like the following: Vue.component('child-comp',{ props:['name', 'val'], data: function(){ return { picked: '' } }, ...

The act of initiating a new server on cPanel is resulting in a 503 service unavailability

I'm encountering an issue while trying to deploy my NextJS app on a shared hosting server using the cPanel Node.JS App Setup feature. Despite receiving the message ready on http://localhost:3000 during the build process, the site is displaying a 503 e ...

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

Identifying if a function is within the prototype chain of a class instance in ES6

Consider the following ES6 class: class C { x () { } fnIsMethodOfC (fn) { return /* ? */ } } Along with various functions like function y () {} z = () => {} What is an efficient way to determine if a function is a method of C, for example: c = ...

Combining hover and mousedown event listeners in jQuery: Tips and tricks

htmlCODE: <div class="original_circle" style="border-radius: 50%; background-color: blue; width: 40px; height:40px; z-index: 0"> <div class="another_circle" style="position:absolute; border-radius: 50%; background-color: coral; width: 40px; h ...

Is there a way to target a button within an anchor tag without relying on a specific id attribute?

On my webpage, I have buttons that are generated dynamically using PHP from a MySQL table. Each button is wrapped in an anchor tag and when clicked, it triggers a Javascript function to carry out multiple tasks. One of these tasks requires extracting the ...

What is the best way to delete a document and all of its nested documents in MongoDB?

In my Mongoose schema, I have defined the following: var postSchema = mongoose.Schema({ title: String, body: String, created: Date, photos: Array }); var Post = mongoose.model('Post', postSchema); var photoSchema = mongoose.Schema({ ...

"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page. My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and v ...

Dealing with Errors in the Body of REST Requests with Spring WebClient

Just starting out with Spring Boot, looking for some guidance. I'm using WebClient to make a GET request and receiving a JSON response like this: { "status": "OK", "error": [], "payload": { ...

JavaScript Vanilla | Object that can be invoked and also has a property

In an assignment, I was given the following task: fun4(): must return an object that can be called as a function. This object should also have a 'k' property with a null value (so fun4()() should perform some action). The first part of the qu ...