1

I'm starting to learn JavaScript, and i am having some difficulties for displaying the whole data i got from Json PlaceHolder fake API on my html table. Using the code below i just manage to display the last element from the API itself, and not all elements as i wanted.

Can someone help me figure it out how should i actually do?

There's the code:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML = 
    `<td>${element.userId}</td>
    <td>${element.id}</td>
    <td>${element.title}</td>
    <td>${element.body}</td>`
  }

1
  • 2
    When you call x.innerHTML = y; multiple times, you keep overwriting the content of x. Only the last y will be visible. You need to wrap your table cells in <tr> and </tr> and use the += operator instead, which adds what's on the right to what's on the left of it. Commented Mar 2, 2021 at 23:40

1 Answer 1

1

Your code is showing one data because when the loop goes it are overwrites the previous one when it loop through the json, change the opperand to += and wrap the table columns with rows <tr>... </tr>
Try this code here

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML +=
    `<tr>
        <td>${element.userId}</td>
        <td>${element.id}</td>
        <td>${element.title}</td>
        <td>${element.body}</td>
    </tr>`
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, i got it now! It worked. Thank you!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.