1

I've tried to create a subclass of HTMLDivElement, but I've got an error: Uncaught TypeError: Illegal constructor

var subC = function() {
    HTMLDivElement.call(this);

    //....
};

subC.prototype = Object.create(HTMLDivElement.prototype);
Iter Ator
  • 8,226
  • 20
  • 73
  • 164

2 Answers2

0

How about

function subC() {
    //w/e
}    
subC.prototype = document.createElement('div');
var x = new subC();
alert(x instanceof HTMLDivElement);

http://jsfiddle.net/vK96X/

Musa
  • 96,336
  • 17
  • 118
  • 137
0

You cant subclass most of the DOM api ,especially things like Node,Element ...

Why? because they involve complex dependency injection,that's why you need to build Element through document.createElement.

The only thing you can do is use composition :

function subC = function(htmlElement){
   this.htmlElement=htmlElement;
}

you can then expose some properties of htmlElement in subC

Object.keys(this.htmlElement).forEach(function(k){this[k]=this.htmlElement[k];},this);

in the constructor,as shortcuts.

You'd need to wrap each method you want to use though,i wouldnt risk adding Element.prototype methods to subC and expect them to behave correctly.

mpm
  • 20,148
  • 7
  • 50
  • 55
  • Some years have passed since this answer and I guess that with the introduction of [custom html elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#customized_built-in_elements) one should be able to subclass quite a lot of the DOM api, otherwise this construct would be pointless ... – Sebastian Nov 05 '22 at 20:27