I want to create my own set of HTML Elements with Web Components, which all include some basic functionality.
I wanted to start with an input and it seems like there are two possibilities:
Either inherit from HTMLElement
or from HTMLInputElement
.
Option A :
class BasicCustomHTMLElement extends HTMLElement {
//basic functionality
}
class CustomInput extends BasicCustomHTMLElement {
let shadow = this.attachShadow({
mode: 'open'
});
let textbox = document.createElement("input");
shadow.appendChild(textbox);
}
Option B
class CustomInput extends HTMLInputElement {
}
My problem with Option B ist, that I do not have a main class
, where I can define basic functionality. On the other hand I have to rewrite Code in Option A for functionality that the native input and select elements offer.
Are there some aspects I am overlooking?
There is no reason that you can't combine option A and option B so that you extend from HTMLInputElement
initially with a base class and then extend that with more specific classes later.
class BasicCustomHTMLElement extends HTMLInputElement {
}
class CustomInput extends BasicCustomHTMLElement {
}
If you want a shared set of features to extend a number of built-in classes with you can use mixins.
const BaseClassMixin = (superclass) => class extends superclass {
};
class CustomInput extends BaseClassMixin(HTMLInputElement) {
}
class CustomTextArea extends BaseClassMixin(HTMLTextAreaElement) {
}
However, currently only Chrome supports extending built-in elements so it is not recommended for real-world use.