JavaScript

Create Element Helper

by @admin
9h ago
Apr 28, 2026
Public
A concise helper for creating DOM elements with attributes, properties, styles, event listeners, and children in one call — similar to hyperscript or JSX without a build step. Eliminates repetitive createElement / setAttribute / appendChild chains and keeps DOM construction code readable.
JavaScript
function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  for (const [key, val] of Object.entries(props)) {
    if (key.startsWith('on') && typeof val === 'function') {
      node.addEventListener(key.slice(2).toLowerCase(), val);
    } else if (key === 'style' && typeof val === 'object') {
      Object.assign(node.style, val);
    } else {
      node[key] = val;
    }
  }
  node.append(...children.flat().map((c) =>
    c instanceof Node ? c : document.createTextNode(String(c))
  ));
  return node;
}

// Usage
const card = el('div', { className: 'card' },
  el('h2', {}, 'Hello'),
  el('button', { onClick: () => alert('hi!') }, 'Click me')
);
document.body.appendChild(card);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.