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