Home > other >  Using fetch API to get JSON from a url, is there function that allows me to create unique DIVs for e
Using fetch API to get JSON from a url, is there function that allows me to create unique DIVs for e

Time:11-14

Using something like this to get JSON

fetch('https://jsonplaceholder.typicode.com/posts')

is there a JS function that would allow me to create a div for each string in the received JSON?

I've tried trying to alter the code below to satisfy my needs, but have been failing.

  const promise = fetch ( 'https://jsonplaceholder.typicode.com/posts');
  promise .then (( response ) => {  
  return response.json ();
  })
  .then(data => {
    data.forEach(sentence => {
      const markup = `
        <p>${sentence.title}</p>
        <p>${sentence.body}</p>
      `;
      document.querySelector('.square').insertAdjacentHTML('beforeend', markup)
    });
  })
  .catch(error => console.log(error));

CodePudding user response:

const promise = fetch ( 'https://jsonplaceholder.typicode.com/posts');
  promise .then (( response ) => {  
  return response.json ();
  })
  .then(data => {
    data.forEach(sentence => {
      const markup = `
        <p>${sentence.title}</p>
        <p>${sentence.body}</p>
      `;
      // Creating a div
      const divElem = document.createElement("div")
      divElem.id = "whatever";
      divElem.classList.add("class1", "class2", "etc");
      divElem.innerHTML = markup;
      document.querySelector(".square").insertAdjacentElement("beforeend", divElem)
    });
  })
  .catch(error => console.log(error));
<div  ></div>

  • Related