Main focus: Implementing dynamic data writing in this particular code scenario

Having trouble dynamically writing data inside my HTML table using JavaScript. As a newcomer to frontend development, specifically JS, I am seeking guidance on making this work smoothly. I've attempted methods like .innerHTML and .innerText without much success. Here are my files index.html and app.js for anyone willing to assist. Thank you in advance!

HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Trainee React Developer</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header class="header-section">
    <h1>Star Wars API Fetch</h1>
  </header>

  <main class="main-content">
    <h3>Here's Star Wars fetched data: </h3>
    <div id="sw-data">
      <table id="table">
        <thead id="t-header">
          <tr id="row-headings">
            <th>Name</th>
            <th>Eye Color</th>
            <th>Height</th>
            <th>Birth Year</th>
            <th>Number of vehicles</th>
          </tr>
        </thead>
        <tbody id="table-content">
            <tr>
               <td id="name-data"></td>
               <td id="eye-color-data"></td>
               <td id="height-data"></td>
               <td id="birth-year-data"></td>
               <td id="vehicles-data"></td>
            </tr>
        </tbody>
      </table>
    </div>
  </main>

  <script src="app.js"></script>
</body>

</html>

JS Code:

   const urlFetch = 'https://swapi.dev/api/people/'; /*fetch request address*/
                    
let charNameCell = document.getElementById('name-data');
let charEyeColorCell = document.getElementById('eye-color-data');
let charHeightCell = document.getElementById('height-data');
let charBirthYearCell = document.getElementById('birth-year-data');
let charVehiclesCell = document.getElementById('vehicles-data');

const fetchAPI = async () => {//Fetching data function
    try {
        const response = await fetch(urlFetch);
        const data = await response.json();
        console.log(data.results); 
       
        data.results.forEach(result => {
            console.log(result); 
            charNameCell.innerHTML = result.name;
            charEyeColorCell.innerHTML = result.eye_color;
            charHeightCell.innerHTML = result.height;
            charBirthYearCell.innerHTML = result.birth_year;
            charVehiclesCell.innerHTML = result.vehicles.length;
          
        });  
    } 
    catch {   
       console.log('Oops, something went wrong!');
    } 
     finally {
        console.log("Fetch session completed!");
    }
}

fetchAPI();

Answer №1

Although your code is generally well-written, it currently only populates data in a single row within the table. To dynamically populate the table, consider removing the existing row and related JS variables associated with the table cells. Instead, reference the table body to populate a new row for each result, as shown below:

const urlFetch = 'https://swapi.dev/api/people/'; /*fetch  request address*/
                    
let tableBody = document.getElementById('table-content');

const fetchAPI = async () => {//Fetching data function
  try {
      const response = await fetch(urlFetch);
      const data = await response.json();

      data.results.forEach(result => {
          const row = tableBody.insertRow(-1),
            nameCell = row.insertCell(-1),
            eyeColorCell = row.insertCell(-1),
            heightCell = row.insertCell(-1),
            birthYearCell = row.insertCell(-1),
            vehiclesCell = row.insertCell(-1);
            
          nameCell.appendChild(document.createTextNode(result.name));
          eyeColorCell.appendChild(document.createTextNode(result.eye_color));
          heightCell.appendChild(document.createTextNode(result.height));
          birthYearCell.appendChild(document.createTextNode(result.birth_year));
          vehiclesCell.appendChild(document.createTextNode(result.vehicles.length));
          
          result.vehicles.length === 0 && vehiclesCell.classList.add('highlight');
      });  
  } 
  catch {   
     console.log('Oops, something went wrong!');
  } 
   finally {
      console.log("Fetch session completed!");
  }
}

fetchAPI();
.highlight {
  border: 1px red solid;
}
<main class="main-content">
    <h3>Here's Star Wars fetched data: </h3>
    <div id="sw-data">
      <table id="table">
        <thead id="t-header">
          <tr id="row-headings">
            <th>Name</th>
            <th>Eye Color</th>
            <th>Height</th>
            <th>Birth Year</th>
            <th>Number of vehicles</th>
          </tr>
        </thead>
        <tbody id="table-content">
        </tbody>
      </table>
    </div>
  </main>

Edit - In response to a comment, I have added a line to highlight a cell when the character has no vehicle. This feature can be expanded as needed.

result.vehicles.length === 0 && vehiclesCell.classList.add('highlight');

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

Tips for adjusting CSS font sizes within a contenteditable element?

I am looking to develop a compact HTML editor using JavaScript that allows me to customize the font-size of selected text with a specific CSS value. The documentation states that the FontSize command is used like this: document.execCommand("FontSize", fal ...

Issue with Vue3: The imported module is not defined

Update: I recently downgraded vue-cli to version 4.5.19 and now the code is functioning properly. It seems like there might be an issue related to vue-cli or its dependencies. I encountered a problem while working on a simple vue.js project using vue-cli. ...

Harnessing conflict in HTML with various versions of jQuery can be a powerful tool for enhancing the

Is it possible to use 2 different jQuery libraries on the same HTML page? I came across some blogs mentioning conflicts, but when I tried to add them both, I had no luck. Can anyone assist me with this? Here is my code: Product slider <link hre ...

Is recursion effective in this scenario? (javascript/node.js)

Currently, I am working on creating a TV using a Raspberry Pi and JavaScript to play the same playlist repeatedly. Although playing the files is not an issue, I am facing a challenge with the asynchronous nature of JavaScript. Below is the code that is cau ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

Rails with Ajax: The destroy.js.erb file has been rendered successfully, but the specific div element identified by its id is not being successfully

Trying to implement a feature where users can click an unfollow button to end a friendship using ajax. However, the div does not disappear even though the console indicates that destroy.js.erb was rendered successfully. The expected outcome is for the reco ...

Achieve a full-screen width container in Bootstrap 4 without using the container-fluid class

Is there a way to make the container have a 100% width using media queries so that the elements are contained in a larger screen but not contained in a small one, or vice versa? This code is just an example that used to work with Bootstrap v4 alpha 6, but ...

A stateless component in React must always return a valid React element or null

I am a beginner with ReactJS and I am facing an issue. My goal is to showcase Hello world using the code snippet provided below, however, I keep encountering this error message: Can someone guide me on what I might be overlooking? The following is the c ...

Transform the inline style attributes found in the HTML code into CSS styling

After creating a webpage using Bootstrap Studio, I realized that all the style attributes are inline and I want to move them to a separate CSS file. However, I am facing difficulty in doing so as when I add an image using 'background-image:url('i ...

Modifying the hue of Material UI tab label

I attempted to modify the label color of a tab to black, but it seems to be stuck as white. Is this color hard-coded in material-ui? If not, how can I change it? Here's what I've tried: const customStyles = { tab: { padding: '2p ...

My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js. After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project. However, I encountered some interesting error ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Rearranging an array while preserving the initial sorting order

My challenge involves handling an array of employee information that is organized by comparing the subdepartment of each employee to the priority of subdepartments within a particular department. When a user clicks on an employee's name in an index, ...

Ways to detect events even after the object has been swapped out in JavaScript

I am currently developing a JavaScript-based Scrabble game and encountering a puzzling issue. The problem arises when tiles are generated within a tile rack div using a specific function, and an event listener is set up to respond to clicks on the tile div ...

Can a JavaScript (NodeJS) command or function be executed without halting the program in case of an error?

Is there a way in JavaScript to execute a function without interrupting the program if an error occurs? player.play('./sounds/throughQueue.mp3', function(err){ // let the program continue execution even if ther ...

The PDF document appears quite different from the original HTML page it was created from

Is there a way to create a PDF document that mirrors the appearance of a web page using jsPdf? When attempting this, it seems that the font size, text alignment, and table alignment of the resulting PDF do not match that of the original web page. Additiona ...

Creating properly formatted HTML strings using C#

Does anyone know of a C# equivalent to the Beautify Code function found on ? For example, I have this string: <div><div><input type="radio" value="radio" id="radio_0">Radio</div><div><input type="radio" value="radio" id="r ...

What is the method for sending a down arrow key in Capybara?

My unique requirement involves a specialized listbox automation that would benefit from simulating a down arrow keystroke and then pressing enter. The code snippet for pressing enter looks like this: listbox_example = find(input, "listbox-example") listb ...

Creating a carousel with three thumbnails arranged in two rows

Currently, I am using a slider for my thumbnails. If you want to check out the code for this thumbnail slider, click on this link: thumbnails slider code My goal is to display 6 thumbnails in total, with 3 thumbnails shown in each row (2 rows total). Add ...

What is the best way to efficiently query a substantial dataset using Node.js in an asynchronous fashion?

I need to extract data from a mysql database by fetching 10 rows at a time until I reach 400k rows. To achieve this asynchronously, I am using recursion as shown in the code below: var migrate = function(offset, size) { Mysql.query(query, [offset, size] ...