Joseph
Joseph

Reputation: 113

Javascript add element to a dynamic div

I'm trying to add some checkbox to a dynamically-created div and after append the div to a static div. but I'm getting this error:

TypeError: Cannot read property 'appendChild' of null

I get this error in this line:

document.getElementById(newDiv).appendChild(checkbox));

Code

function func(staticDiv){
   var newDiv = document.createElement("DIV");
   var checkbox = createCheckbox();

   document.getElementById(newDiv).appendChild(checkbox);
   document.getElementById(staticDiv).appendChild(newDiv);

}

 function createCheckbox() {
     var checkbox = document.createElement("INPUT");
     checkbox.setAttribute("type", "checkbox");
     checkbox.setAttribute("name", "checkbox");
    return checkbox;
 }

Upvotes: 2

Views: 2091

Answers (3)

danwellman
danwellman

Reputation: 9253

The issue is that you are passing the newDiv element that you just created to the getElementById method, which should take a string.

You probably want to just do:

function func(staticDiv){
    var newDiv = document.createElement("DIV");
    var checkbox = createCheckbox();

    newDiv.appendChild(checkbox);
    document.getElementById(staticDiv).appendChild(newDiv);
}

Upvotes: 0

Rob
Rob

Reputation: 127

Here is Your full code Code

 function func(staticDiv){
   var newDiv = document.createElement("DIV");
   var checkbox = createCheckbox();

   newDiv.appendChild(checkbox);
   document.getElementById(staticDiv).appendChild(newDiv);
 }

 function createCheckbox() {
   var checkbox = document.createElement("INPUT");
   checkbox.setAttribute("type", "checkbox");
   checkbox.setAttribute("name", "checkbox");
   return checkbox;
 }

It's causes because you are trying to get newly created Div wit ID, but you div has'nt ID :)

Upvotes: 1

laurent
laurent

Reputation: 90746

Since newDiv is the actual element, you can simply do this:

newDiv.appendChild(checkbox);
staticDiv.appendChild(newDiv);

Upvotes: 0

Related Questions