Home > OS >  create divs and divs in other divs with img based on the number of elements in an array
create divs and divs in other divs with img based on the number of elements in an array

Time:01-22

I have an array with three elements.

I need to create a unique <div class = "mySlides fade"> for each element of the array, so for each image, with div class = "numbertext" changing for each element (so for the first element 1/3, for the second 2/3 and so on), img src which automatically takes the name of the images.

Then using a for loop on length dev create the div present below (I repeat a single div which then changes automatically when the i of the for takes its value).

for(var i = 0; i < myArr.length; i ) --> this is to iterate through the array

document.getElementById("example").innerHTML = myArr[i] --> this to "fetch" the names of the images

var  myArr = ['img_nature_wide.jpg','img_snow_wide.jpg','img_mountains_wide']

<div >

    <div >
      <div >1 / 3</div>
      <img src="img_nature_wide.jpg" style="width:100%">
    </div>

    <div >
      <div >2 / 3</div>
      <img src="img_snow_wide.jpg" style="width:100%">
    </div>

    <div >
      <div >3 / 3</div>
      <img src="img_mountains_wide.jpg" style="width:100%">
    </div>

</div>

My problem is in "juggling" the set of divs with img

Sorry if I ask this, but unfortunately I'm new to programming

CODE ADDED

suppose besides that div I put above, I also have the div as put in the code below.

What should I do if I have a code made in the following way?

//this is what i put already
<div >

<div >
</div>

<div >
</div>

<div >
</div>

</div>
<br>

// this is the new div
<div>
  <span  onclick="myFunction(i)"></span>  
</div>

CodePudding user response:

Try this one using template literal and for loop.

var myArr = ['img_nature_wide.jpg', 'img_snow_wide.jpg', 'img_mountains_wide']
for (var i = 0; i < myArr.length; i  ) {
  document.querySelector('.slideshow-container').innerHTML  = `
    <div >
      <div >${i 1} / 3</div>
      <img src="${myArr[i]}" style="width:100%">
    </div>
 `
 document.querySelector('#final').innerHTML  =`
 <span  onclick="myFunction(${i})"></span> 
`
}
console.log(document.body.innerHTML)
<div >

<div >
</div>

<div >
</div>

<div >
</div>

</div>
<br>

<div id='final'>
  <span  onclick="myFunction(i)"></span>  
</div>

  •  Tags:  
  • Related