Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix Javascript associative array error

I am trying to display a list of images with their titles stored in an associative array. But the code only displays the last image and title in the array, in the browser not all of them. However when I console log the values: value.title and value .image the full list is displayed in the console. I must be missing something simple any pointers would be welcome.

<center id="pics"></center>
    <script>
      const photos = [
        {
          title: "Landscape River",
          image: "landscape1.png",
        },
        {
          title: "Landscape Mountains",
          image: "landscape2.png",
        },
        {
          title: "Landscape Mountain Road",
          image: "landscape3.png",
        },
        {
          title: "Landscape Hills and Lake",
          image: "landscape4.png",
        },
      ];

      photos.forEach((value) => {
        console.log(value.title, value.image);
       
          document.getElementById("pics").innerHTML =
            `<img src="images/${value.image}" >` + "<br>" + value.title;
        
      });
    </script>
  </body>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You will want to do document.getElementById("pics").innerHTML += instead of just =. You want to append each title and image, and not reset the innerHTML every time with a new title/image if that makes sense. Happy coding!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading