Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Haralds Cerins
Haralds Cerins
2,516 Points

create div tags with different IDs using for loop in java script

Im iterating through an array and want to insert values in separate divs and use the array indexes to create id="day[i]" for divs. Here's the code, no idea why it's not working:

{

var day = "" ;   
    for (var i in daily.list)
    {

        day += "<div id=" + day + i + ">"; 
        day += daily.list[i].pressure;
        day += "</div>";

        }

    }

5 Answers

David Bath
David Bath
25,940 Points

Craig is right, you're not using the for-in loop correctly. If you do it this way, i is actually holding the item from item.list, not a loop variable like 1, 2, 3. It might be better to use a regular for loop like this:

var day = "";
for (var i=0; i < daily.list.length; i++) {
  day += "<div id='day" + i + "'>"; 
  day += daily.list[i].pressure;
  day += "</div>"
}

Hi Haralds,

Can you provide some more of the code.

for (i = 0; i < 5; i++) {
    text += "The number is " + i + "<br>";
}

The above is a simple version of a for loop, to me you are not adding the iterator to the i.

Craig

Haralds Cerins
Haralds Cerins
2,516 Points

var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var daily = JSON.parse(xhr.responseText);

var day = "" ;
for (var i in daily.list) {

    day += "<div id=" + day + i + ">"; 
    day += daily.list[i].pressure
    day += "</div>"

    }

}

    document.getElementById("container").innerHTML= day;
}

xhr.open("GET", 'daily.json'); xhr.send();

Haralds Cerins
Haralds Cerins
2,516 Points

So the script is to display json data of weather forecast for 5 days and I want to display each day in separate divs and assign each div id="day[i]" so I would be able to change display state onclick for each day.

Haralds Cerins
Haralds Cerins
2,516 Points

Cool, thank you guys, it's working now.