Skip to content

Instantly share code, notes, and snippets.

@devcutler
Last active January 24, 2022 01:06
Show Gist options
  • Save devcutler/0070c4d68909723f7bd9b65204d5b4cc to your computer and use it in GitHub Desktop.
Save devcutler/0070c4d68909723f7bd9b65204d5b4cc to your computer and use it in GitHub Desktop.
A basic function to create a simple HTML element in a one-liner.
/**
* @author [arynthernium](https://github.com/arynthernium)
* @param {string} tag Can be any valid HTML tag.
* @param {string} innerHTML String to set as the innerHTML of the returned node.
* @param {object} attrs An object of attributes to be applied with setAttribute.
* @param {object} styles Object with valid JS style keys for CSS styles.
* @returns {HTMLElement}
*/
function create(tag = 'div', innerHTML = '', attrs, styles) {
const node = document.createElement(tag);
node.innerHTML = innerHTML;
Object.keys(attrs).forEach(key => {
node.setAttribute(key, attrs[key]);
});
Object.assign(node.style, styles);
return node;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment