Created
March 15, 2017 00:32
-
-
Save taylorlapeyre/bee1fae9065c3aa54c86492cccbe4a8e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function createElement(tagName, options, ...children) { | |
// If the "tagName" is a function, we assume it is a custom element and delegate element creation to it. | |
// Otherwise, we create a new Element ourselves. | |
const isCustomElement = typeof tagName === 'function' | |
const element = isCustomElement ? tagName(options) : document.createElement(tagName) | |
if (!options) { | |
return element | |
} | |
// "options" may contain a special key called `events` - more on that later. | |
const { events, ...domAttributes } = options | |
for (const attributeName in domAttributes) { | |
// If we were passed a custom element, then we already delegated this work to it. | |
// Othwerwise, here we are assign any various HTML properties (className, src..) to the new element. | |
if (!isCustomElement && domAttributes.hasOwnProperty(attributeName)) { | |
element[attributeName] = domAttributes[attributeName] | |
} | |
} | |
// `events` is a map of event names to corresponding event handlers. | |
// As before, if we were a custom element then we already took care of this work. | |
if (!isCustomElement && events) { | |
for (const eventName in events) { | |
if (events.hasOwnProperty(eventName)) { | |
element.addEventListener(eventName, events[eventName]) | |
} | |
} | |
} | |
// Finally, we append any children we were given. If a child is text, we put it in a <span>. | |
if (children) { | |
children.forEach((child) => { | |
if (child instanceof Element) { | |
element.appendChild(child) | |
} else { | |
element.appendChild(document.createTextNode(child)) | |
} | |
}) | |
} | |
return element | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment