Skip to content
Advertisement

How to display images in JS using loop?

I have this function, and I’m trying to display photos using a loop. in name1 I have the file location of the photos, every loop I change the photo so the location is obviously changed. in console.log I do see the file, for example "cardImages/7_of_diamonds.png".

now the problem that I have is that I don’t really understand how to display the photos and keep them there, so I have 2 ways that I found but they don’t actually work. and the end result should look like the photo I added to the post. the first loop for the ph1 id. and the second loop for the ph2 id. what I’m missing here? example

   //$("#ph1").append("<img src='name1'>");

    //result.innerHTML = "<img src=''${name2}'' alt='ph2' />";

 

     function DisplayUsingLoop(pla1, numb1) {
                var name1;
              
    
                for (i = 0; i < numb1; i++) {
    
                    name1 = pla1[i].img
                    console.log(name1)
                   result.innerHTML = "<img src=''${name2}'' alt='ph2' />";
                }

                for (i = 0; i < numb2; i++) {
    
                    name1 = pla2[i].img
                    console.log(name1)
                    $("#ph1").append("<img src='name1'>");   
                }


<body>
    <input type="button" value="Start" onclick="start()" />
    <div id="container">

        <div id="ph1">
            Player 1:
           

        </div>

        <div id="ph2">
            Player 2:



        </div>
    </div>
                
    
    
                

Advertisement

Answer

To display photos using a loop, use the for loop. First of all, you need to put your js inside of tags, like this:

<script>
//this is js
</script>

Player1:

//this is js
let div = document.getElementById(`ph1`)
for (let i = 0; i < 5; i++) {
div.innerHTML += `<img src=`your_image_file_name`></img>`
}

if you want different images each time, then manually do it without a loop:

//this is js
let div = document.getElementById(`ph1`)

div.innerHTML += `<img src='img1.png'></img>`

div.innerHTML += `<img src='img2.png'></img>`

Also, try to learn js and html using w3schools before you start coding this stuff.

Also, you are using jQuery, which you need to import using html before you start your js.

Also, try using strict html formatting and put js at the end of your body.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement