简体   繁体   中英

javascript document.getelementbyid() doesn't work with looping on html load

I coded a function to fill 6 div's in my index.html by trying to get every div id. I want that to happen when the page is loaded.

What happen is the image only fill in the 6th div where what I want is the image to be loaded inside all the div with id='flip-card'.

I put 'console.log(i)' inside the for-loop to check if the loop works. It is working but somehow doesn't want to fill all the div with image, it only fill the last one.

Can anyone help me what did I miss here? Very appreciate your help

this is my index.html file

<div id="container-project-5">
    <h1>MEMORY GAME</h1>
    <div class="container-flip-row">
      <div id="flip-card-1" class="flip-card-spot"></div>
      <div id="flip-card-2" class="flip-card-spot"></div>
      <div id="flip-card-3" class="flip-card-spot"></div>
    </div>
    <div class="container-flip-row">
      <div id="flip-card-4" class="flip-card-spot"></div>
      <div id="flip-card-5" class="flip-card-spot"></div>
      <div id="flip-card-6" class="flip-card-spot"></div>
    </div>
  </div>

<script src="loadimage.js"></script>

this is my js file

function loadImage() {
  let img = document.createElement("img");
  img.src = "https://static8.depositphotos.com/1000792/861/v/950/depositphotos_8614495-stock-illustration-fun-zoo-koala.jpg";
  
  img.setAttribute("width", "150px");
  img.setAttribute("height", "150px");
  
  //THIS loop SUPPOSE to FILL ALL the <div> with id 'flip-card' BUT SOMEHOW it ONLY FILL the 6th <div> which is <div id='flip-card-6" class='flip-card-spot'>
  for (let i = 1; i <= 6; i++) {
    document.getElementById("flip-card-" + i).appendChild(img);
    //this is console log to check if for-loop is working
    console.log(i);
  }
}

//LOAD FUNCTION when BROwSER is LOADED
window.addEventListener("load", loadImage);

this is my css

<style>

.flip-card-spot {
  display: flex;
  margin: 1px;
  background-color: green;
  width: 150px;
  height: 150px;
}

.container-flip-row {
  display: flex;
}

</style>

You're appending the same image element each time. Move the code that creates the element inside the loop too, so that you create multiple elements instead, or use cloneNode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM