DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Custom JavaScript CreateElement Function
Ahmed Adel
Ahmed Adel

Posted on

Custom JavaScript CreateElement Function

• One of the most common functions to create HTML elements dynamically using Vanilla JS is Document.createElement() which takes 1 parameter which is the tag name, this function returns the newly created element, then after that you will write some code to add properties or attributes to it then append it to another element in your DOM.

• This process usually takes many lines which makes creating a simple html structure a headache.

• So let me introduce a simple function that can make this process easier :

    let createElement= (initObj)=> {
        var element = document.createElement(initObj.Tag);
        for (var prop in initObj) {
            if (prop === "childNodes") {
                initObj.childNodes.forEach(function (node) { element.appendChild(node); });
            }
            else if (prop === "attributes") {
                initObj.attributes.forEach(function (attr) { element.setAttribute(attr.key, attr.value) });
            }
            else element[prop] = initObj[prop];
        }
        return element;
    }
Enter fullscreen mode Exit fullscreen mode

So, let's see what this function can do:

  • Create the html element normally.
  • Add attributes to it (Key value pairs).
  • Add any custom property or events to it
  • Add child nodes to this element

All in one line

How to use it:

  • First of all, this function takes an object that must have a property named Tag, to specify the element Tag name:
let myElement = CreateElement({Tag:'div'});
Enter fullscreen mode Exit fullscreen mode
  • To add an id and some classes for example:
let myElement = CreateElement(
{
   Tag:'div',
   id:'myId',
   classList:'btn btn-danger'
});
Enter fullscreen mode Exit fullscreen mode
  • To add an on click function and an inner html:
let myElement = CreateElement(
{
   Tag:'div',
   innerHTML:"<i class='fas fa-trash-alt'></i>",
   onclick:yourOnClickFunction()
});
Enter fullscreen mode Exit fullscreen mode

and it is the same for all object properties or even new properties you need to add to the object.

  • To add attributes with keys & values:
let myElement = CreateElement(
{
   Tag:'div',
   attributes:
   [
     {key:'customAttr1': , value: '500'},
     {key:'customAttr2': , value: 'ABC'},
   ],
});
Enter fullscreen mode Exit fullscreen mode
  • To add Child Nodes to this node after it is created:
let myElement = CreateElement(
{
   Tag:'div',
   childNodes: [nodeElement1 , nodeElement2],
});
Enter fullscreen mode Exit fullscreen mode

This is how easy you can use it🤷‍♂️
It's a function that I love to use in each project I am involved in.
Hope you like it 👋

Top comments (2)

Collapse
 
tomsoderlund profile image
Tom Söderlund • Edited on

Thank you! This was my take, to mimic React.createElement:

function createElement (elementType, props, children) {
    const element = document.createElement(elementType)
    for (const prop in props) {
        if (prop === 'style') {
            Object.keys(props.style).forEach(function (styleName) { element.style[styleName] = props.style[styleName] })
        } else if (props[prop] !== null) {
            element[prop] = props[prop]
        }
    }
    if (children) {
        children.forEach(function (node) { element.appendChild(node) })
    }
    return element
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
milanwake profile image
Moon Presence

Thank you! 🤓

Quite an interesting option. Of course, it can be supplemented or even improved, but this is probably a matter of taste and requirements. 🤓

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!