Search code examples
javascriptgetelementbyidconsole.log

How can I show the output in console.log?


I am trying to fetch data from an api into console and then display it on a page.

I have correctly fetched the data from the placeholder api into console.log, but I cannot display it onto the page in the div. What am I doing wrong?

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

document.getElementById("console")
<div id="console"></div>


Solution

  • If you just want to output the data as a formatted string you could create a function to "pretty print" the stringified data using <pre> and <code>.

    const output = document.querySelector('.output');
    
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(updateHTML);
    
    function updateHTML(data) {
      const json = JSON.stringify(data, null, 2);
      const html = `<pre><code>${json}</code></pre>`;
      output.insertAdjacentHTML('beforeend', html);
    }
    <div class="output"></div>

    If you wanted to display the data differently (in a table, for example) you could iterate (map) over the keys and values returned by Object.entries to return a string of row HTML, and add that html to the page.

    const output = document.querySelector('.output');
    
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(updateHTML);
    
    function updateHTML(data) {
    
      // Get the object entries - and array of key/value pairs
      const entries = Object.entries(data);
    
      // Iterate over the entries and return a new array
      // of strings created from the key/value using a
      // template string.
      const rows = entries.map(([key, value]) => {
        return `
          <tr>
            <td class="heading">${key}</td>
            <td>${value}</td>
          </tr>
        `;
      });
    
      // Create a new HTML string by `join`ing up the row array
      // and adding it to a new string
      const html = `<table><tbody>${rows.join('')}</tbody></table>`;
    
      // Insert the HTML into the page
      output.insertAdjacentHTML('beforeend', html);
    }
    table { background-color: #efefef; border-collapse: collapse; border: 1px solid #afafaf; }
    td { padding: 0.4em; border: 1px solid white; }
    .heading { text-transform: uppercase; text-align: right; font-weight: 500; background-color: #dfdfdf; }
    <div class="output"></div>

    Addition documentation