Home > Software engineering >  Get more than 1 API element and add to the table in HTLM
Get more than 1 API element and add to the table in HTLM

Time:12-29

I need to GET the id, title and completed element from the API below, but my scrip that I am studying gets only the id, but I need all the elements in the table, how can I get it?

is it possible to get lines instead of list?

enter image description here

CodePudding user response:

You'll need to create an tr before appending for each cell (td) in the table.

function fetchApiData(){
    fetch('https://jsonplaceholder.typicode.com/todos/')
    .then((response) => response.json())
    .then((data) => {
    
        const tbody = document.querySelector('tbody');
    
        data.map((item) => {
            const tr = document.createElement('tr');
            
            for (let k in item) {
                let td = document.createElement('td');
                td.innerHTML = item[k]
                tr.appendChild(td);
            }
            
            tbody.appendChild(tr)
        });
    })
}

fetchApiData()
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
<table>
    <tbody>
    </tbody>
</table>

  • Related