April 22, 2013
For loop not creating Div
Fstephen07’s Questions:
I’m attempting to create multiple divs on the fly by using a for loop. This code does not give any results. My expectation is for it to create separate divs with the id a1,a2,a3, etc. Can anyone explain why it doesn’t? I understand there are other solutions to this on SO, but this is a learning experience for me and I want to know why my solution does not work.
function createDiv(divid,divcontent){
this.div = document.createElement("div");
this.div.setAttribute("id",divid);
this.div.innerHTML = divcontent;
}
var keys = [1,2,3,4,5,6,7,8,9,0];
for (i=0; i<keys.length;i++){
createDiv("a"+i,i);
}
You’ll have to append the node to a parent – existing – node in the document to make it appear. Like this:
function createDiv(divid,divcontent){
this.div = document.createElement("div");
this.div.setAttribute("id",divid);
this.div.innerHTML = divcontent;
var parent = document.getElementById('mydiv');
parent.appendChild(this.div);
}
Your function only creates the div
you have to add it to the DOM
function createDiv(divid,divcontent){
this.div = document.createElement("div");
this.div.setAttribute("id",divid);
this.div.innerHTML = divcontent;
}
var keys = [1,2,3,4,5,6,7,8,9,0];
for (i=0; i<keys.length;i++){
var newDiv = createDiv("a"+i,i); //Store the div you just created here
document.getElementById('yourdivcontainer').appendChild(newDiv); //And add it to the DOM
}