Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. /**
  2. * A simple helper for creating nested dom tree inspired by snabbdom-jsx syntax
  3. * @param {string} name
  4. * @param {{[attr: string]: any}} attrs
  5. * @param {Array<HTMLElement | string>} children
  6. * @returns {HTMLElement}
  7. */
  8. export function createElem(name, attrs, children) {
  9. const elem = document.createElement(name);
  10.  
  11. for (const [attr, val] of Object.entries(attrs || {})) {
  12. const match = attr.match(/^(prop|class|on|)-([\w-]+)$/);
  13. if (match) {
  14. const [_, prefix, name] = match; // eslint-disable-line no-unused-vars
  15. if (prefix === `prop`) {
  16. elem[name] = val;
  17. } else if (prefix === `class` && val) {
  18. elem.classList.add(name);
  19. } else if (prefix === `on`) {
  20. elem.addEventListener(name, val);
  21. }
  22. } else {
  23. elem.setAttribute(attr, val);
  24. }
  25. }
  26.  
  27. if (!Array.isArray(children)) {
  28. children = [children];
  29. }
  30.  
  31. for (const child of children) {
  32. if (typeof child === `string`) {
  33. elem.appendChild(document.createTextNode(child));
  34. } else if (child) {
  35. elem.appendChild(child);
  36. }
  37. }
  38.  
  39. return elem;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement