The aim of this puzzle: Use a for...of loop
to add information from a database of animals to a webpage.
Walkthrough of the solution: In the code that you start off with, a for...of
loop iterates through an animals
array that’s imported from additional code. The for…of loop creates an h2 and img element for each animal
in the animals
array and appends them to the body
.
In this puzzle, you’ll create a paragraph element for each animal
in the animals
array and append it underneath each image element.
To complete the puzzle, inside the for..of loop
, make a variable called description
that stores a new paragraph element using document.createElement('p')
. Then, set its text content to animal[2]
. Finally, append the description
element to the body
. In order for each paragraph to go below each photo, be sure to append the description
after the line that appends the image, body.appendChild(img)
.
Sample code solution:
(Tap below to reveal)
JavaScript
import { animals } from 'cuteAnimals.data';
let title = document.createElement('h1');
title.textContent = 'Cute Animals';
document.body.appendChild(title);
for (let animal of animals) {
let name = document.createElement('h2');
name.textContent = animal[0];
let img = document.createElement('img');
img.src = animal[1];
let description = document.createElement('p');
description.textContent = animal[2];
document.body.appendChild(name);
document.body.appendChild(img);
document.body.appendChild(description);
}
HTML Concepts:<p>
, <img>
, <h2>
,
JavaScript Concepts: .textContent,
.createElement(), document, body,
.appendChild()`, for…of loop, import statement, variables