This content originally appeared on DEV Community and was authored by Ahmed Adel
• 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;
}
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'});
- To add an id and some classes for example:
let myElement = CreateElement(
{
Tag:'div',
id:'myId',
classList:'btn btn-danger'
});
- 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()
});
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'},
],
});
- To add Child Nodes to this node after it is created:
let myElement = CreateElement(
{
Tag:'div',
childNodes: [nodeElement1 , nodeElement2],
});
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 ?
This content originally appeared on DEV Community and was authored by Ahmed Adel
Ahmed Adel | Sciencx (2021-08-28T13:24:38+00:00) Custom JavaScript CreateElement Function. Retrieved from https://www.scien.cx/2021/08/28/custom-javascript-createelement-function/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.