Skip to content
Advertisement

How do I iterate the array, then show all the elements in HTML? [closed]

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?

const backpackContents = ["piggy", "headlamp", "pen"];
backpackContents.forEach(function (item) {
  document.querySelector("body").innerHTML = `<li>${item}</li>`;
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Console demo</title>
    <script src="script.js" defer></script>
  </head>
  <body></body>
</html>

Advertisement

Answer

As @Rocky Sims said in comments change .innerHTML = to .innerHTML +=

const backpackContents = ["piggy", "headlamp", "pen"];
backpackContents.forEach(function(item) {
  document.querySelector("ul").innerHTML += `<li>${item}</li>`;
})
<ul>
</ul>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement