Difference between revisions of "DOM content from lists"

From ProgZoo
Jump to navigation Jump to search
Line 40: Line 40:


== Using forEach ==
== Using forEach ==
<div class=qu>
*An alternative is the forEach method
*An alternative is the forEach method
<pre class=usr>
<pre class=usr>

Revision as of 08:52, 26 August 2021


beatles.json

{"members":
 [
   {"firstName":"Paul","lastName":"McCartney"},
   {"firstName":"John","lastName":"Lennon"},
   {"firstName":"Ringo","lastName":"Starr"},
   {"firstName":"George","lastName":"Harrison"}
 ]
}

Using a for loop

  • When you have data in a list you can use a for loop to generate content
fetch('/beatles.json')
  .then((r)=>r.json())
  .then((r)=>{
    for(let b of r.members){
      let div = document.createElement('div');
      div.innerHTML = `${b.lastName}, ${b.firstName}`;
      document.body.append(div);
    }
  });

fetch('/beatles.json')
  .then((r)=>r.json())
  .then((r)=>{
    for(let beatle of r.members){
      let div = document.createElement('div');
      div.innerHTML = `${beatle.firstName} ${beatle.lastName}`;
      document.body.append(div);
    }
  });

Using forEach

  • An alternative is the forEach method
fetch('/beatles.json')
  .then((r)=>r.json())
  .then((r)=>{
    r.members.forEach(b => {
      let div = document.createElement('div');
      div.innerHTML = `${b.lastName}, ${b.firstName}`;
      document.body.append(div);
    })
  });

fetch('/beatles.json')
  .then((r)=>r.json())
  .then((r)=>{
    r.members.forEach(b => {
      let div = document.createElement('div');
      div.innerHTML = `${b.firstName} ${b.lastName}`;
      document.body.append(div);
    })
  });