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);
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;
}
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"
})
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 :)
Top comments (2)
change appendTo to elementAppendTo
in the very last document.querySelector(appendTo).append(element) call
Thank you for the info :)