Looping through an array to div?

I'm trying to add a p element containing a single month in this string to a div with the id of "write". How do I get this loop to run through the list of strings and add them to the div?

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"];
var element = document.getElementById("write").innerHTML = months;
for (var i = 0; i <= months; i++) {
var para = document.createElement("p");
var text = document.createTextNode(i);
}

I don't understand why it isn't working. Thanks!

Upvotes: 0

Views: 32

Answers (1)

Barmar
Barmar

Reputation: 782785

It looks like you're totally misunderstanding how to use arrays, you need to go back to your tutorials and study this.

You need to use months.length as the limit of the array, not just months. You should use <, not <= in the test, because otherwise you'll go past the end of the array. And in the text node you should put months[i], not just i. Then you need to make the text node a child of the paragraph. You can't set the innerHTML of an element to an array; you should be adding the paragraphs as children of the element.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var element = document.getElementById("write");
for (var i = 0; i < months.length; i++) {
  var para = document.createElement("p");
  var text = document.createTextNode(months[i]);
  para.appendChild(text);
  element.appendChild(para);
}
<div id="write"></div>

Upvotes: 3

Related Questions