Cannot add to dom an onbject that has an elements as a prototype

97 views Asked by At

Consider this setup:

function makeObj(a){
   this.foo = 'bar';
   this.prototype = a;
}

b = makeObj(document.getElementById('foo'));
document.getElementById('bar').appendChild(b);

this gives an error:

Node cannot be inserted at the specified point in the hierarchy" code: "3

Why so? Object b has a valid element as its prototype. Shouldn't it have worked?

1

There are 1 answers

1
jfriend00 On

There are several issues here.

First makeObj() isn't making a new object at all. It's just a function call and this in that function call is likely referring to the window object. You would have to use makeObj() with the new operator to actually create a new javascript object.

Secondly, you can only append DOM objects to the DOM, not regular javascript objects.

Thirdly, just assigning a DOM object to another object's prototype does not make that other object suddenly become a DOM object. If you want a DOM object, you need to create a DOM object using something like createElement() or one of the other documented ways of creating DOM objects.

If you can describe more about what you're really trying to accomplish, we could advise further.