DEV Community

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 👋

Discussion (0)