DOM content from lists: Difference between revisions
Jump to navigation
Jump to search
| Line 11: | Line 11: | ||
} | } | ||
== | == Using a for loop == | ||
*When you have data in a list you can use a for loop to generate content | *When you have data in a list you can use a for loop to generate content | ||
<pre class=usr> | <pre class=usr> | ||
| Line 17: | Line 17: | ||
.then((r)=>r.json()) | .then((r)=>r.json()) | ||
.then((r)=>{ | .then((r)=>{ | ||
for(let | for(let b of r.members){ | ||
let div = document.createElement('div'); | let div = document.createElement('div'); | ||
div.innerHTML = | div.innerHTML = `${b.lastName}, ${b.firstName}`; | ||
document.body.append(div); | document.body.append(div); | ||
} | } | ||
| Line 34: | Line 34: | ||
document.body.append(div); | document.body.append(div); | ||
} | } | ||
}); | |||
</pre> | |||
</div> | |||
== Using forEach == | |||
*An alternative is the forEach method | |||
<pre class=usr> | |||
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); | |||
}) | |||
}); | |||
</pre> | |||
<pre class=ans> | |||
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); | |||
}) | |||
}); | }); | ||
</pre> | </pre> | ||
</div> | </div> | ||
Revision as of 07:51, 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);
})
});