Skip to content

Instantly share code, notes, and snippets.

@erdesigns-eu
Last active August 29, 2024 10:54
Show Gist options
  • Save erdesigns-eu/b54c872e034798b648a260af0fec1a6b to your computer and use it in GitHub Desktop.
Save erdesigns-eu/b54c872e034798b648a260af0fec1a6b to your computer and use it in GitHub Desktop.
JSX DOM
type Attrs = {
[key: string]: any;
};
const h = (tag: string, attrs: Attrs, ...children: (Node | string)[]): HTMLElement => {
const elm = document.createElement(tag);
for (let key in attrs) {
if (key.startsWith('on')) {
const evtName = key.slice(2);
const cb = attrs[key];
if (cb === null) {
continue;
}
elm.addEventListener(evtName, cb);
}
else if (['disabled', 'autocomplete', 'selected', 'checked'].includes(key)) {
if (attrs[key]) {
elm.setAttribute(key, key);
}
}
else {
if (attrs[key] === null) {
continue;
}
elm.setAttribute(key, attrs[key]);
}
}
if (children.length > 0) {
children.flat().forEach((child) => {
if (child instanceof Node) {
elm.appendChild(child);
}
else {
elm.appendChild(document.createTextNode(child));
}
});
}
return elm;
};
@erdesigns-eu
Copy link
Author

erdesigns-eu commented Aug 29, 2024

Example:

// Create a div with some attributes and nested elements
const myDiv = h(
  'div',
  { id: 'container', className: 'my-container', onclick: () => alert('Container clicked!') },
  h('h1', {}, 'Hello World!'),
  h('p', {}, 'This is a paragraph within the container.'),
  h('button', { onclick: () => alert('Button clicked!') }, 'Click Me')
);

// Append the generated HTML structure to the document body
document.body.appendChild(myDiv);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment