-1

I have some 72 pics names fun1,fun2......fun72... So instead of writing 72 img tags I just wanna create img tags using Script. But I am unable to loop between these 72 pics because I have no idea of how to call for loop variable inside a String.

Method 1

// For images
let pics = document.getElementById("pics-thumbs");
let divholder = document.createDocumentFragment();
for (let i = 1; i < 73; i++) {
    let img = document.createElement("img");
    img.class = "img-responsive";
    img.src = "images/fun+i.jpg";
    divholder.appendChild(img);
}
pics.appendChild(divholder);

Method 2

// For images
let pics = document.getElementById("pics-thumbs");
let divholder = document.createDocumentFragment();
for (let i = 1; i < 73; i++) {
    let img = document.createElement("img");
    img.class = "img-responsive";
    img.src = "images/fun" + i ".jpg";
    divholder.appendChild(img);
}
pics.appendChild(divholder);
0

2 Answers 2

2

You could do like this

DEMO

let pics = document.getElementById("pics-thumbs"),
  imgArr = [];
for (let i = 1; i < 73; i++) {

  imgArr.push(`<img class="img-responsive" src="images/fun${i}.jpg">`);
}
pics.innerHTML = imgArr.join('<br>')
<div id="pics-thumbs"></div>

Sign up to request clarification or add additional context in comments.

2 Comments

Nice and easy code...Thanks a lot
@GvsAkhil hearty welcome
1

Use

img.src="images/fun" + i + ".jpg";

Or, with EcmaScript 6,

img.src=`images/fun${i}.jpg`;

It is called concatenation.

3 Comments

oops i missed a + after my i
And does it work now? If yes you can mark as solved. If no please post additional error messages you might get.
ya its asking wait fr 10 mins to mark it as solved

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.