Skip to content

Instantly share code, notes, and snippets.

@nchevobbe
Last active August 22, 2021 12:03
Show Gist options
  • Save nchevobbe/d1ea6d5354707a44ed03a209e10cf727 to your computer and use it in GitHub Desktop.
Save nchevobbe/d1ea6d5354707a44ed03a209e10cf727 to your computer and use it in GitHub Desktop.
Utility function to create DOM element
/**
* Utility function to create DOM element with populated attributes and content
*
* Usage :
*
* // simple element
* let input = createDomElement("input", {
* type: "search",
* placeholder: "Enter what pleases you"
* });
*
* // simple element with HTML content
* let label = createDomElement("label", {},
* "<span>Hit <kbd>Esc</kbd> to close</span>"
* );
*
* // simple element with click handler
* let input = createDomElement("div", {
* listeners: {
* click: e => console.log("clicked", e)
* }
* }, "Click me!");
*
* // nested elements
* createDomElement("div", {
* "class": "tab-item",
* },
* createDomElement("label", {},
* createDomElement("input", {type: "radio", name: "type"}),
* "A"
* ),
* createDomElement("label", {},
* createDomElement("input", {type: "radio", name: "type", "disabled": true}),
* "B"
* )
* )
*
* @param {String} tagName
* @param {Object} attributes
* @param {String|Object} items
* @returns {Element}
*/
function createDomElement(tagName, attributes = {}, ...items) {
let element = document.createElement(tagName);
for ([attributeKey, attributeValue] of Object.entries(attributes)) {
if (attributeKey === "listeners") {
for ([eventName, handler] of Object.entries(attributeValue)) {
element.addEventListener(eventName, handler);
}
} else if(attributeValue) {
element.setAttribute(attributeKey, attributeValue)
}
}
if (items.length > 0) {
let docFrag = document.createDocumentFragment();
for (childEl of items) {
if(typeof childEl === "string") {
let div = document.createElement("div");
div.innerHTML = childEl;
while (div.childNodes.length > 0) {
docFrag.appendChild(div.childNodes[0]);
}
} else if(childEl) {
docFrag.appendChild(childEl);
}
}
element.appendChild(docFrag);
}
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment