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
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!