I’m learning javascript, I try my best to use correct “word” to describe my question 🙂 This is my code, now it could only show the last item of the array to HTML, I thought forEach should iterate the while array to get all elements populate to HTML… anyone could give me some suggestion?
JavaScript
x
4
1
const backpackContents = ["piggy", "headlamp", "pen"];
2
backpackContents.forEach(function (item) {
3
document.querySelector("body").innerHTML = `<li>${item}</li>`;
4
});
JavaScript
1
10
10
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8" />
5
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
<title>Console demo</title>
7
<script src="script.js" defer></script>
8
</head>
9
<body></body>
10
</html>
Advertisement
Answer
As @Rocky Sims
said in comments change .innerHTML =
to .innerHTML +=
JavaScript
1
4
1
const backpackContents = ["piggy", "headlamp", "pen"];
2
backpackContents.forEach(function(item) {
3
document.querySelector("ul").innerHTML += `<li>${item}</li>`;
4
})
JavaScript
1
2
1
<ul>
2
</ul>