Skip to content

Instantly share code, notes, and snippets.

@nickytonline
Last active December 11, 2024 01:13
Show Gist options
  • Save nickytonline/8223b27b19c080c28d9f0d3b7fce1e82 to your computer and use it in GitHub Desktop.
Save nickytonline/8223b27b19c080c28d9f0d3b7fce1e82 to your computer and use it in GitHub Desktop.
A Handy DOM element creation function.
// Inspired from Sam Thorogood's article, https://dev.to/chromiumdev/beyond-appendchild-better-convenience-methods-for-html-55n4
function createElement(nodeName, props) {
const { style = {}, ...propsNoStyle } = props;
const element = Object.assign(document.createElement(nodeName), propsNoStyle);
for (const key in style) {
element.style[key] = style[key];
};
return element;
}
@samthor
Copy link

samthor commented Jul 11, 2019

👍

@nickytonline
Copy link
Author

nickytonline commented Dec 10, 2024

This could use a refresh after reading https://bsky.app/profile/developit.dev/post/3lcwby5wkfs2l from @developit.

function createElement(nodeName, props) {
  const { style = {}, ...propsNoStyle } = props;
  const element = Object.assign(document.createElement(nodeName), propsNoStyle);

  for (const key in style) {
    element.style[key] = style[key];
  };

  return element;
}

@samthor
Copy link

samthor commented Dec 11, 2024

My 2c: I get that doing a loop is technically better but holy microoptimization, batman.

Use whatever is easier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment