Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active November 16, 2020 20:53
Show Gist options
  • Save Phoenix35/761651684a25cfb6923c10a969544271 to your computer and use it in GitHub Desktop.
Save Phoenix35/761651684a25cfb6923c10a969544271 to your computer and use it in GitHub Desktop.
"use strict";
/**
* @param {string} tagName .
* @param {object} [options] .
* @param {string} options.className - The CSS class(es) to give to the node. Takes precedence over classList
* @param {string[]} options.classList - The CSS classes to give to the node
* @param {object<string, (string|number)>} options.style - The CSS style(s) to additionally give to the node
* @param {string} options.textContent - The content of the node
* @param {...<string, (string|number)>} options.attributes - Any other attributes to give to the node
* @return {Node} The custom created node
*/
export function createNode (tagName, { className, classList, style, textContent, ...attributes }) {
const node = document.createElement(tagName);
if (className)
node.className = className;
else if (classList != null && classList.length !== 0)
node.classList.add(...classList);
if (style)
Object.assign(node.style, style);
if (textContent)
node.textContent = textContent;
for (const [k, v] of Object.entries(attributes))
node.setAttribute(k, v);
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment