PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

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

 August 13, 2022     dom, javascript     No comments   

Issue

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>


Solution

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>



Answered By - TAHER El Mehdi
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing