0

Ok, I have a literal arrays where there are some images in it. I have an empty DIV where a FOR LOOP will be carried out to display all the images in the array in the div.

var icons = [
    '<img src="images/1.png" width="30" height="30"/>',
    '<img src="images/2.png" width="30" height="30"/>',
    '<img src="images/3.png" width="30" height="30"/>'
    ];

    var lol = document.getElementById("div");

    for (var i=0; i<icons.length; i++) {
            lol.innerHTML = icons[i] ;
        }

The issue is only the last image is displayed not all...

1
  • Better use DOM manipulation rather than innerHTML. Commented Nov 3, 2012 at 8:05

3 Answers 3

1

That is because you are overwriting the previous image with the current one. If you want to append/concat all images, use +=:

lol.innerHTML += icons[i];

A better way to handle this would be to use DOM handling:

var img = document.createElement("img");
img.setAttribute("src", icons[i]);

lol.appendChild(img);
Sign up to request clarification or add additional context in comments.

3 Comments

i prefer the += lol.innerHTML.... as if someone wants to add an image, just just it in the array...
That works with the DOM handling to. Just put my last snippet inside your for-loop.
@user1780468 Yeah, that works, but innerHTML is just as evil as document.write. It can easily break the DOM if careless. That's why I prefer DOM manipulation with the use of document.createElementand document.createTextNode.
0

Each time you do

lol.innerHTML = icons[i];

you're replacing the inner HTML of the div with icons[i]. Concatenate all your icon elements, and then set the inner HTML of the div with the result of the concatenation.

Comments

0

your code is overwrite the innerHTML you can append the innerHTML

try this

lol.innerHTML += icons[i];

this above code is append the innerHTML

or in jquery you can use append function

$('#div').append(icons[i]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.