Can you extend HTMLDivElement in TypeScript?

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

I would like to make this pseudo-class:

class QuizElement extends HTMLDivElement{ } 

Sorry if this question is crazy. I'm a little new to the DOM, and just thought: I can extend any visual class in any other environment, so I think it is useful here!

+9
typescript
source share
3 answers

You cannot extend HTMLDivElement because it is not declared as a class. This makes sense because the main native type does not make sense to expand.

You have two alternative options.

Option 1: Implements!

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

 class QuizElement implements HTMLDivElement { 

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

Option 2: Delegation.

You can provide specific properties and methods that you want to make available in your QuizElement class, and then delegate the actual instance of HTMLDivElement . A 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'; 
+7
source share

You can also "extend" the HTMLDivElement interface using data elements, if you wish, not using extends, since this is not a class, but by adding it through the interface. TypeScript interfaces are "open", see page 85 specifications under "ad aggregation."

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

for example, below is added the element 'mydata' of type string in the HTMLDivElement interface.

 interface HTMLDivElement { mydata : string; } // now we can assign a value var div = <HTMLDivElement>document.getElementById("myDiv"); div.mydata = "test"; 
+7
source share

A bit late, but apparently still not possible to extend HTMLDivElement. A simple way to solve the DIV extension problem: just use CSS to make the generic HTMLE element behave like a div.

CSS

  my-element { display:block; } 

Javascript

 class MyElement extends HTMLElement{ constructor(){ this.innerHTML = "I behave exactly like a div" } } window.customElements.define('my-element', MyElement); 
0
source share

All Articles