0

I'm working with TypeScript without any component framework/library like React or Vue, and I'm creating my DOM components using the document.createElement method, but since I know, this method only allows you to pass the name of the element to be created, and after that I need to set some attributes for the components using the .setAttribute method of them, but depending of the number of attributes, it can take like 5~7 line just doing it.

So, I want to create a overload for this method that can accept more arguments to be the attributes to set and internally it will call the .setAttribute method to set them

Some example:

// The default way to set the attributes
const element = document.createElement("div");

element.setAttribute("attr1", "value1");
element.setAttribute("attr2", "value2");
...
element.setAttribute("attrN", "valueN");

// What I want to do
const element = document.createElement("div", {attr1: "value1", attr2: "value2", ..., attrN: "valueN"});

Note

I think creating an overload for the .createElement method may not be a good practice, because it will change the default behaviour of the document object, so if is there any sugestion of how to handle it, it will be welcome!

1 Answers1

0

Since you will always have only one document, there is no point in putting createElement onto document, just make a new function

I also did one for myself (but with other priorities: by id-class-attr selector, append args), you can check it here: https://github.com/Dimava/PoopJs/blob/master/poopjs/elm.ts#L25

As for proper types, go-to-definition of createElement and copy generics from there.

Basically something like:


export function elm<K extends keyof HTMLElementTagNameMap>(selector: K, attrs?: Record<string, string>): HTMLElementTagNameMap[K];
export function elm<E extends Element = HTMLElement>(selector: string, attrs?: Record<string, string>): E;
export function elm(): HTMLDivElement;
export function elm(selector: string = 'div', attrs: Record<string, string> = {}): HTMLElement {
    let el = document.createElement(selector);
    for (let [k, v] of Object.entries(attrs)) {
        el.setAttribute(k, v);
    }
    return el;
}
Dimava
  • 7,654
  • 1
  • 9
  • 24