Tim Tim - 1 year ago 76
Javascript Question

Can I subclass a DOM-class?

I was wondering if I can create a subclass of HTMLDivElement. Like this.

MyDivElement.prototype.pickColor = function()
return this.picked;
function MyDivElement()
this = new HTMLDivElement();
this.picked = 'unknowd';
alert(this.picked); // print: 'unkowd'

Is (something like) this possible?
If not, what is the best way to achieve this?

Answer Source

new HTMLDivElement(); throws a TypError "Illegal constructor" in Chrome - so it's not possible.

Update: I've tested in other current browsers, and they throw various types of errors - but they all throw.

Actually, this would work:

function MyDivElement() {
    this.picked = 'unknowd';

MyDivElement.prototype = document.createElement('div');

var mydiv = new MyDivElement();

But I'm not sure how you could use this pattern...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download