Question

I have a simple question concerning Javascript. I am trying to print in a loop some values to div container. The problem is that instead printing the value several times in a loop, each time it is overwritten and as a result I get only one value. See the code below:

for (i=0; i<json.Locations.length; i++) {
    var location = json.Locations[i];
    var content = document.getElementById('eventsnearby');                                                    
    var html = location.name;
    content.innerHTML = html;
}

Any ideas welcomed. Thanks.

Was it helpful?

Solution

Append, don't assign.

content.innerHTML += html;

Better yet, use standard DOM.

var content = document.getElementById('eventsnearby');                                                        
for (var i = 0; i < json.Locations.length; i++) {
    var text = json.Locations[i].name;
    var node = document.createTextNode(text);
    content.appendChild(node);
}

OTHER TIPS

You only get one value because you're setting the innerHTML property during each loop iteration instead of appending to it. Try using content.innerHTML += html;.

for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];

var content = document.getElementById('eventsnearby');                                                    
var html = location.name;
content.innerHTML += html;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top