Please advise how to implement an extension class for DOM elements in typescript.
Lets say I want to add two methods enable and disable to the standard DOM element methods.
So far, i have to do this:
export class FormElement {
public element: HTMLElement
constructor(selector: string) {
this.element = document.querySelector(selector)
}
public disable = (): void => {
this.element.setAttribute('disabled', 'disabled')
}
public enable = (): void => {
this.element.removeAttribute('disabled')
}
}
At some place I want to get a DOM element extended by the FormElement class
class SomeComponent {
...
private get nameInput(): FormElement {
return new FormElement('input#company_msisdn')
}
private disableNameInput = (): void => {
this.nameInput.disable()
}
}
Looks good, but if you need to use the DOM methods of an element, it does not look very good:
...
private initializeNameInput = (): void => {
this.nameInput.element.addEventListener('change', this.onNameInputChange)
}
Tell me if there is a way to implement the FormElement class so that the call to the newly added methods and to the DOM methods of the element looked the same:
this.nameInput.enable()
this.nameInput.addEventListener('change', this.onNameInputChange)
?
For example i'm try create class with genric:
class FormElement<T = HTMLElement> {
private this.element
constructor(selector: string) {
this.element = document.querySelector(selector) as T
}
...
}
const nameInput = new FormElement<HTMLInputElement>('#name-input')
nameInput.disable()
nameInput.addEventListener('change', this.onNameInputChange)
But it is not right code, please advise how to implement class and generic.
elementproperty? correct? I still don't understand what is wrong withthis.nameInput.element.addEventListener('change', this.onNameInputChange).element.isnt clear solution for me.const getElementFromDOM = (selector: string) => document.querySelector(selector);where as you can use it:const nameInput = getElementFromDOM(someSelector); nameInput.addEventListener(...)? What I mean is, is a functional approach feasible for you?HTMLElementconstructor?