Use fetch function to access remote data using the given api and display the data in the form of a table.

PHOTO EMBED

Tue Apr 22 2025 18:31:14 GMT+0000 (Coordinated Universal Time)

Saved by @fsd

<!DOCTYPE html>
<html>
<head>
  <title>Fetch API Table</title>
  <style>
    
    th, td {
      border: 1px solid #999;
      padding: 8px 12px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
  </style>
</head>
<body>

<h2 style="text-align:center;">User Data Table</h2>

<table id="userTable">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>City</th>
    </tr>
  </thead>
  <tbody>
    <!-- Data will be inserted here -->
  </tbody>
</table>

<script>
  fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {
      const tableBody = document.querySelector("#userTable tbody");

      data.forEach(user => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td>${user.id}</td>
          <td>${user.name}</td>
          <td>${user.email}</td>
          <td>${user.address.city}</td>
        `;
        tableBody.appendChild(row);
      });
    })
    .catch(error => {
      console.error("Error fetching data:", error);
    });
</script>

</body>
</html>
content_copyCOPY