stephenthedev
stephenthedev

Reputation: 577

For loop not creating Div

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);
}

Upvotes: 0

Views: 152

Answers (4)

Teddy
Teddy

Reputation: 797

function createDiv(id, content){
  var div = document.createElement('div');
  div.setAttribute("id",id);
  div.innerHTML = content;
  return div;
}
var $parent = $('#parentDiv'); // get parent div
$parent.append(createDiv("a"+i,i));

Upvotes: -1

Starx
Starx

Reputation: 78991

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
}

Upvotes: 0

marteljn
marteljn

Reputation: 6516

You need to append your div to an existing html element.

document.getElementById("yourHtmlElementId").appendChild(this.div);

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158030

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);
}

Upvotes: 4

Related Questions