piyush7931
piyush7931

Reputation: 225

Create multiple div using data from array using for loop

I want to assign array elements to multiple divs which also have image tag in them using for loop. Array consists of image paths.

var img_list = ["one.png", "two.png", "three.png", "four.png"];

By using above array I have to create below HTML Structure. All divs should be inside "outer" div with a data-slide attribute which is without ".png".

<div id="outer">
  <div class="slide" data-slide="one"><img src="Images/one.png" /></div>
  <div class="slide" data-slide="two"><img src="Images/two.png" /></div>
  <div class="slide" data-slide="three"><img src="Images/three.png" /></div>
  <div class="slide" data-slide="four"><img src="Images/four.png" /></div>
</div>

This is what I wrote:

for (var i=0; i < img_list.length; i++){
    var container = document.getElementById("outer").innerHTML;
    var new_card = "<div class=\"slide\" data-slide=\'" + img_list[i] + "\'><img src=\'Images/" + img_list[i] + "\' /></div>";
    document.getElementById("outer").innerHTML = new_card;
}

But it is only showing the last image. Please help.

Upvotes: 2

Views: 2146

Answers (7)

Rik
Rik

Reputation: 1987

  1. You can declare your variables outside of the loop and reuse them. This is more efficient.
  2. const and let are preferable to var. You only need to set container once so it can be const. new_card should be let since you need to assign it more than once.
  3. You can also use template string so you don't need all the back slashes.
  4. using forEach will make the code cleaner:

const img_list = ["one.png", "two.png", "three.png", "four.png"];
const container = document.getElementById("outer")
let new_card;
img_list.forEach(i => {
    new_card = `<div class=slide data-slide='${i.split(".")[0]}'><img src='Images/${i}'></div>`
    container.innerHTML += new_card;
})
    <div id="outer">
    </div>

Alternately, using reduce:

const img_list = ["one.png", "two.png", "three.png", "four.png"];
const container = document.getElementById("outer")
const reducer = (a, i) => a + `<div class=slide data-slide='${i.split(".")[0]}'><img src='Images/${i}'></div>`
container.innerHTML = img_list.reduce(reducer, '')
    <div id="outer">
    </div>

Upvotes: 0

Narendra Jadhav
Narendra Jadhav

Reputation: 10262

You could also use map method of array and Element.innerHTML to get the required result.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.


Demo

const img_list = ["one.png", "two.png", "three.png", "four.png"];

let result = img_list.map((v, i) => `<div class="slide" data-slide="${v.split(".")[0]}"><img src="Images/${v}"/>${i+1}</div>`).join('');

document.getElementById('outer').innerHTML = result;
<div id="outer"></div>

Upvotes: 0

Vasu Kuncham
Vasu Kuncham

Reputation: 548

You are almost there but, every time you are overriding the slider div.

You just have to add + at assignments section. like below.

document.getElementById("outer").innerHTML += new_card;

Here is the full example:

var img_list = ["one.png", "two.png", "three.png", "four.png"];

for (var i=0; i < img_list.length; i++){
    var container = document.getElementById("outer").innerHTML;
    var new_card = "<div class=\"slide\" data-slide=\'" + img_list[i].split('.')[0] + "\'><img src=\'Images/" + img_list[i] + "\' /></div>";
    document.getElementById("outer").innerHTML += new_card;
}
<div id="outer"></div>

Upvotes: 0

guest271314
guest271314

Reputation: 1

The code at the question overwrites the .innerHTML within the for loop by setting .innerHTML to new_card at every iteration of the array. You can substitute .insertAdjacentHTML() for setting .innerHTML. Also, substitute const for var to prevent new_card from being defined globally. Include alt attribute at <img> element. You can .split() img_list[0] at dot character ., .shift() the resulting array to get word before . in the string img_list[i] to set data-* attribute value.

const img_list = ["one.png", "two.png", "three.png", "four.png"];

for (let i = 0, container = document.getElementById("outer"); i < img_list.length; i++) {
  const src = img_list[i];
  const data = src.split(".").shift();
  const new_card = `<div class="slide" data-slide="${data}"><img src="Images/${src}" alt="${data}"/></div>`;
  container.insertAdjacentHTML("beforeend", new_card);
}
<div id="outer"></div>

Upvotes: 3

Maheer Ali
Maheer Ali

Reputation: 36564

You are changing the innerHTML you need to add to it. And use Template literals for creating html strings

var img_list = ["one.png", "two.png", "three.png", "four.png"];
const outer = document.getElementById('outer')
img_list.forEach(img => {
  outer.innerHTML += `<div class="slider" data-slide="${img.split('.')[0]}"><img src="Images/${img}" /></div>` 
})
console.log(outer.innerHTML)
<div id="outer">
</div>

Upvotes: 2

Abhishek Raj
Abhishek Raj

Reputation: 490

@Tony7931, please replace the last line of for loop with below code:

document.getElementById("outer").innerHTML += new_card;

Upvotes: 0

Icehorn
Icehorn

Reputation: 1337

Each time your for loop runs, it is replacing the html element within the "outer" div with the current img html.

In order to have it append you can simply change document.getElementById("outer").innerHTML = new_card; to document.getElementById("outer").innerHTML += new_card; so that the element is appended rather than overwritten.

Upvotes: 6

Related Questions