1

Using Javascript, I've pulled a value from an XML document and I'm trying to generate as many tags as the value I've pulled is. I assume I would go about doing this using a for loop, but when I tried this, it would only display one image.

for(i=0; i<red; i++){
   document.getElementById("red").innerHTML = "<img src='slike/red.png'></img>";
}

I'm aware of why this isn't working, but I couldn't find a solution myself, so I'm wondering what Javascript function do I need?

4
  • 3
    Have you tried using += instead of just = ? Commented Jun 17, 2013 at 15:01
  • 2
    If you want to append to the string, use += instead of = (shorthand string concatenation). You could also use DOM manipulation methods, such as .appendChild. Commented Jun 17, 2013 at 15:02
  • 1
    You should consider using a DocumentFragment instead. Commented Jun 17, 2013 at 19:57
  • +1 for document fragment. re rendering DOM with every push is a waste Commented Jun 17, 2013 at 23:40

4 Answers 4

4

Use string concatenation:

html = '';
for(i=0; i<red; i++){
   html += "<img src='slike/red.png'></img>";
}
document.getElementById("red").innerHTML = html;

You could also use += when assigning to .innerHTML in the loop, but that's less efficient because the browser has to format and reparse the DIV contents each time. It's better to do it in one fell swoop.

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

Comments

2

Well, if you think about it logically, it seems that what you've coded is for the innerHTML of red to change "red" number of times. You're not adding the img "red" times, you're just changing it to that one image "red" times.

So, why don't you do this instead:

var numberImages= "";

for(i=0; i<red; i++){
    numberImages += "<img src='slike/red.png' />";
} 

document.getElementById("red").innerHTML= numberImages;

Comments

1

each time it assigns a single vaue to the innerHTML of the element.

use the below instead.

var elem=document.getElementById("red");
for(i=0; i<red; i++){


       elem.innerHTML = elem.innerHTML+"<img src='slike/red.png'></img>";
    }

Comments

0

If you're going to be adding a large number of elements to the DOM, you should be using a DocumentFragment to avoid any unnecessary reflows. Here's a quick example (and a fiddle):

var fragment = document.createDocumentFragment();

for (var i = 0; i < 10; i++)
{
    var img = document.createElement('img');
    img.src = 'slike/red.png';

    fragment.appendChild(img);
}

document.getElementById('red').appendChild(fragment);

What this allows you to do is create as many elements as you need and add them to the DOM in batch which will only reflow the DOM once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.