Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using fetch API to get JSON from a url, is there function that allows me to create unique DIVs for each string of the received JSON?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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));

>Solution :

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 class="square" ></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading