Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extend a HTMLDivElement in TypeScript?

Tags:

typescript

I am making a DOM based game for the first time. I would like to extend HTMLDivElement, however in TypeScript, HTMLDivElement is an Interface.

I would like to do this pseudo class:

class QuizElement extends HTMLDivElement{

}

Sorry if this question is crazy. I am somewhat new to the DOM, and just thought, I can extend any visual class in any other environment so I guess it is do-able here!

like image 994
Clark Avatar asked Jul 18 '14 10:07

Clark


2 Answers

You can't extend HTMLDivElement because it isn't declared as a class. This makes sense, because the underlying native type doesn't make sense to extend.

You have two alternative options.

Option 1: Implements!

Because HTMLDivElement is an interface, you can implement it...

class QuizElement implements HTMLDivElement {

You would have to implement all of the properties and methods of the interface. You probably don't want to do this.

Option 2: Delegation.

You can expose the specific properties and methods you want to make available on your QuizElement class and then delegate to an actual HTMLDivElement instance. Quick example below:

class QuizElement {
    private element: HTMLDivElement;

    constructor(id: string) {
        this.element = <HTMLDivElement>document.getElementById(id);
    }

    set innerHTML(content: string) {
        this.element.innerHTML = content;
    }
}

var quizElement = new QuizElement('quiz');

quizElement.innerHTML = 'Example';
like image 182
Fenton Avatar answered Sep 22 '22 13:09

Fenton


A bit late, but apparently it's still not possible to extend HTMLDivElement. A simple way to solve extending a DIV: just use CSS to make a generic HTMLElement behave like a div.

CSS

 my-element {
    display:block;
 } 

Javascript

class MyElement extends HTMLElement{
  constructor(){
      super()
      this.innerHTML = "I behave exactly like a div"
  }
}

window.customElements.define('my-element', MyElement);
like image 23
Kokodoko Avatar answered Sep 24 '22 13:09

Kokodoko