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!
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';
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With