Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. function renderApp(selector, children) {
  2. const app = document.querySelector(selector)
  3. appendChildren(app, children)
  4. }
  5.  
  6. function domElements() {
  7. const elements =
  8. ['div', 'ul', 'li', 'p', 'h1', 'img']
  9.  
  10. return elements.reduce((els, el) => {
  11. els[el] = createElement.bind(null, el)
  12. return els
  13. }, {})
  14. }
  15.  
  16. function createElement(type, options, children) {
  17. if (
  18. arguments.length === 2 &&
  19. (Array.isArray(options) || typeof options === 'string')
  20. ) return createElement(type, {}, options)
  21.  
  22. const el = applyProps(document.createElement(type), options)
  23.  
  24. if (typeof children === 'string') {
  25. appendText(el, children)
  26. } else if (Array.isArray(children)) {
  27. appendChildren(el, children)
  28. }
  29.  
  30. return el
  31. }
  32.  
  33. function applyProps(el, props) {
  34. Object.keys(props)
  35. .filter(prop => prop in el)
  36. .forEach(prop => el[prop] = props[prop])
  37.  
  38. return el
  39. }
  40.  
  41. function appendChildren(parent, children) {
  42. const fragment = document.createDocumentFragment()
  43. children.forEach(child => fragment.appendChild(child))
  44. parent.appendChild(fragment)
  45. return parent
  46. }
  47.  
  48. function appendText(el, text) {
  49. const textNode = document.createTextNode(text)
  50. el.appendChild(textNode)
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement