Difference between revisions of "DOM working with data"

From ProgZoo
Jump to navigation Jump to search
Line 62: Line 62:
== Include image ==
== Include image ==
<div class=qu>
<div class=qu>
<div class=imper>Include div elements and an img for country 150</div>
<div class=imper>Include div elements and an img for country 151</div>
<pre class=usr>
<pre class=usr>
fetch('/worldl.json')
fetch('/worldl.json')
Line 76: Line 76:
   .then((r)=>r.json())
   .then((r)=>r.json())
   .then((r)=>{
   .then((r)=>{
     let tgt = r[150];
     let tgt = r[151];
     document.body.innerHTML = `
     document.body.innerHTML = `
<div>Name: ${tgt.name}</div>
<div>Name: ${tgt.name}</div>

Revision as of 11:03, 22 August 2021


Get the name from the number

  • You can obtain data from the server using a fetch call.
  • In these examples you will be getting data from /worldl.json this is a list of 195 countries in json format
  • The program snippet shows the name of country 42.
  • Change it so it shows the name of country 50.
  • See if you can find your country.
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[42];
     document.body.innerHTML = tgt.name;
  });
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[50];
     document.body.innerHTML = tgt.name;
  });

Each country has a bunch of data associated, for example:

area: 330803
capital: "Kuala Lumpur"
continent: "Asia"
flag: "//upload.wikimedia.org/wikipedia/commons/6/66/Flag_of_Malaysia.svg"
gdp: 304726000000
id: 102
name: "Malaysia"
population: 30177000
tld: ".my"

Show the population

Alter your code so that the output matches the model answer.
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[102];
     document.body.innerHTML = 
       `<div>${tgt.name}</div>`;
     });
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[102];
     document.body.innerHTML =
       `<div>${tgt.name}, ${tgt.capital}</div>`;
  });

Include image

Include div elements and an img for country 151
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[151];
     document.body.innerHTML = 
       `<div>${tgt.name}, ${tgt.capital}</div>`;
     });
fetch('/worldl.json')
  .then((r)=>r.json())
  .then((r)=>{
     let tgt = r[151];
     document.body.innerHTML = `
<div>Name: ${tgt.name}</div>
<div>Capital: ${tgt.capital}</div>
<div>Population: ${tgt.population}</div>
<img src='${tgt.flag}' style='width:100px'/>
`;
     });