William
William

Reputation: 4588

How to create a simple DOM element within a constructor and append it to an element on invocation

The comments should be self explanatory. I simply want to create an element in a constructor and have it appended to the DOM when an object is created with it.

<div id="app">

</div>

Javascript

function DomItem(name,buttonName,button){ 

if(typeof(this.button)==='undefined') {
    this.button  =   document.createElement('div');
};

this.buttonName = buttonName;
this.button.className = buttonName;
this.button.id = name +"_ " +buttonName;
var app = document.getElementById("app");   //Works!
console.log(app);                          // Works!
app.appendChild(button);                  // Problem ~~~~~~~~~~~~~~~




};



osc = new DomItem('osc','button');

Upvotes: 0

Views: 673

Answers (1)

c.P.u1
c.P.u1

Reputation: 17094

button within the DomItem constructor function is undefined since you are not passing in the third button parameter. Any named parameter that isn't passed is assigned the value undefined.

osc = new DomItem('osc','button'/*, button parameter missing*/);

Use this.button to refer to the button created within the constructor.

app.appendChild(this.button); 

Note that this.button in the below code doesn't refer to the third button argument but to a property button of this, which will always be undefined on calling the constructor.

if(typeof this.button ==='undefined') {
    this.button = document.createElement('div');
}

Upvotes: 2

Related Questions