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

After making an AJAX call using fetch(), how do I append a P tag in an HTML list?

I am new and not afraid of working on a problem and I’m grateful for all the knowledge available. But I have tried and failed for too long now.

// 1. GET request using fetch()
fetch("https://jsonplaceholder.typicode.com/todos")
  // Convert received data to JSON
  .then(response => response.json())
  .then(users => show(users));

  function show(users) {
    const para = document.querySelector("p");
    for (let user of users) {
      let html = `<p>${user.title}</p>`;
        para.insertAdjacentHTML("afterend", html);
    }
  };
 <ul> <!-- loop start -->
    <li>
      <img src="https://picsum.photos/200" />
      <p></p> <!-- append to <p>${users.title}</p> for each obj -->
    </li>
  </ul> <!-- loop end -->

Of course that will loop the P tag with user.title for each json object. But that’s as far as I get… lots of successful variations though building a new list.

I keep going back to thinking I’m close with something like:

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

Array.from(document.querySelectorAll('p'))
  .forEach(p => {
  p.innerHTML = p.innerHTML
    .replace();
})

But I just am not sure and cant get it even close enough to know I may be on the right track. I know the replace() method isn’t right, and ‘replaceWith()’ is Jquery… is this where the show function woudl run? I keep coming back to this as I did something similar in a tutorial and it seems frustratingly close.

I’m not asking anyone to do it for me ’cause then I won’t learn but even a hint would be inspiring enough to drive me to invest countless more hours. Still, beats the other sh!t I could be doing at my age, like sleeping. Cheers ~

>Solution :

Use document.createElement to make <li> elements to add to the unordered list with Element#append.

fetch("https://jsonplaceholder.typicode.com/todos")
  .then(response => response.json())
  .then(users => show(users));

function show(users) {
  const ul = document.querySelector('ul');
  for (const user of users) {
    const li = document.createElement('li');
    const p = document.createElement('p');
    p.textContent = user.title;
    li.append(p);
    ul.append(li);
  }
}
<ul></ul>
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