element-builder.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function parseTagName (selector) {
  2. if (!selector.includes('.')) {
  3. return [selector, null];
  4. }
  5. let tagName = selector.substring(0, selector.indexOf('.'));
  6. let classes = selector.substring(selector.indexOf('.') + 1);
  7. let classList = classes.split('.');
  8. return [tagName ?? 'div', classList];
  9. }
  10. function el (selector, ...args) {
  11. let attributes = null;
  12. if (typeof args[0] === 'object' && !args[0].nodeType) {
  13. attributes = args.shift();
  14. }
  15. // Extract a tag name and any number of class names from the first argument.
  16. let [tagName, classList] = parseTagName(selector);
  17. let element = document.createElement(tagName);
  18. if (attributes) {
  19. // If an object is given as a second argument, it's a list of
  20. // attribute/value pairs.
  21. for (let [attr, value] of Object.entries(attributes)) {
  22. element.setAttribute(attr, value);
  23. }
  24. }
  25. // Any further arguments are children of the element.
  26. for (let item of args) {
  27. if (!item) continue;
  28. if (typeof item === 'string') {
  29. item = document.createTextNode(item);
  30. } else if (Array.isArray(item)) {
  31. // This is an array; append its children, but do not append it.
  32. for (let n of item) {
  33. element.appendChild(n);
  34. }
  35. continue;
  36. }
  37. element.appendChild(item);
  38. }
  39. if (classList) {
  40. element.classList.add(...classList);
  41. }
  42. return element;
  43. }
  44. module.exports = el;