DEV Community

Sooraj (PS)
Sooraj (PS)

Posted on • Edited on

14 7

Generic Snippets - DOM Element Creation

Hey guys, here is one of my generic javascript snippets that helped me when I was working with DOM elements using Vanilla Javascript.

For a very long time, I was used to writing stuff like

let element = document.createElement('div');
element.setAttribute("class", "my-class");
element.style.background = "red";
element.innerText = "Hello";
element.addEventListener('click', function(event) {
  event.preventDefault();
  console.log("Clicked!")
})
document.body.append(element);
Enter fullscreen mode Exit fullscreen mode

all across the code.

Even though this code was only around 10 lines, It was repeated in so many places across the project. So I came up with this generic snippet that is defined only once in the entire project. It might look big, but I found it very useful when working with multiple DOM element creation.

const createElement = function({ type, styles, attributes, props, eventHandlers, appendTo }) {
  let elementType = type || 'div';
  let elementStyles = styles || {};
  let elementAttributes = attributes || {};
  let elementProps = props || {};
  let elementEventHandlers = eventHandlers || {};
  let elementAppendTo = appendTo || 'body';

  let element = document.createElement(elementType);
  for (let key in elementStyles) { element.style[key] = elementStyles[key] }
  for (let key in elementAttributes) { element.setAttribute(key, elementAttributes[key]) }
  for (let key in elementProps) { element[key] = elementProps[key] }
  for (let key in elementEventHandlers) { element.addEventListener(key, elementEventHandlers[key]) }
  document.querySelector(elementAppendTo).append(element);
  return element;
}
Enter fullscreen mode Exit fullscreen mode

The function took all the commonly used properties and attributes of an element and looped them and applied the respective properties.

Since the type, style, attr, props and events were commonly used everywhere, I added those as the params. Finally I added the appendTo param, because obviously when we create an element, we need to add to the HTML DOM right. This function helped me save lots of time by just calling it like this

createElement({
  type: 'button',
  styles: {
    "color": "#fff",
    "background-color": "#3da6ed",
    "border-radius": "2px",
    "border": "none",
    "outline": "none",
    "cursor": "pointer"
  },
  attributes: {
    "class": "p-3"
  },
  props: {
    "innerText": "Click Me!"
  },
  eventHandlers: {
    "click": handleButtonClick
  },
  appendTo: "#element-creator"
})
Enter fullscreen mode Exit fullscreen mode

This function call would create a button with all the attributes, props and styles and attach a click listener. The syntax was also really easy to understand.

So this is one the snippets that I use whenever I work with only Vanilla JS. Hope you guys find it useful :)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (2)

Collapse
 
p0rsche profile image
Vladimir Gerasimov

change appendTo to elementAppendTo
in the very last document.querySelector(appendTo).append(element) call

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Thank you for the info :)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay