Created
September 9, 2020 20:16
-
-
Save dcabines/f9ed59f9d3569930da11828a9c0ad6cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function element<e extends HTMLElementTagNameMap[keyof HTMLElementTagNameMap]>( | |
tag: keyof HTMLElementTagNameMap, | |
attributes: { [k in keyof HTMLParagraphElement]?: string; }, | |
events: { [k in keyof HTMLElementEventMap]?: string; }, | |
...children: HTMLElement[] | |
): e { | |
const element = document.createElement(tag) as e; | |
Object.keys(attributes).forEach(key => { | |
if (key === 'innerText') { | |
element.innerText = attributes[key]; | |
return; | |
} | |
element.setAttribute(key, attributes[key]); | |
}); | |
Object.keys(events).forEach(key => { | |
element.addEventListener(key, events[key]); | |
}); | |
children.forEach(child => element.appendChild(child)); | |
return element; | |
} | |
function div( | |
attributes: { [k in keyof HTMLParagraphElement]?: string; }, | |
events: { [k in keyof HTMLElementEventMap]?: string; }, | |
...children: HTMLElement[] | |
): HTMLDivElement { | |
return element<HTMLDivElement>('div', attributes, events, ...children); | |
} | |
function p( | |
attributes: { [k in keyof HTMLParagraphElement]?: string; }, | |
events: { [k in keyof HTMLElementEventMap]?: string; }, | |
...children: HTMLElement[] | |
): HTMLParagraphElement { | |
return element<HTMLParagraphElement>('p', attributes, events, ...children); | |
} | |
function span( | |
attributes: { [k in keyof HTMLParagraphElement]?: string; }, | |
events: { [k in keyof HTMLElementEventMap]?: string; }, | |
...children: HTMLElement[] | |
): HTMLSpanElement { | |
return element<HTMLSpanElement>('span', attributes, events, ...children); | |
} | |
div( | |
{ title: 'This is a div.' }, | |
{}, | |
p( | |
{ title: 'This is a paragraph.' }, | |
{}, | |
span( | |
{ innerText: 'This is a span.' }, | |
{} | |
) | |
) | |
); | |
// Creates: | |
// <div title="This is a div."><p title="This is a paragraph."><span>This is a span.</span></p></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment