The DOM Nodes Factory

The DOM node factory, somewhere by the Black Sea in Năvodari, Romania

Hello folks, here we are with another quick tutorial. We will learn how to create a function that generates DOM nodes for us and one that deletes them. In this frontend world we often need to create and delete nodes so why not create our own set of tools to do this tedious job.
Also, just to be fancy, let’s create a class for the sake of it. If you don’t know what is a class, don’t worry, I don’t know either. Let’s assume a class is a way to group common functionality and values. So, we will define a class with exactly two methods: one to create a DOM node and another to delete a DOM node.
Let’s get going, shall we?

class DOMFactory {
// the next lines of code will be added here
}

Inside the class let’s define some default node name for our factory. Let’s assume the user will create divs most of the time :) It’s static so we can call it like DOMFactory.defaultName.

static defaultNodeName = 'div';

And here is our create function. It’s static so we can call it directly without having to create a new object from the class. If I lost you don’t worry, you did not loose much. You can still follow through this tutorial.

static create(content = '', nodeName = DOMFactory.defaultNodeName) {
}

We pass two parameters: content and nodeName in case the user want’s to create something else than a div. Now, inside out create function we will create a DOM node. We will try to create it using the node name specified by the user but in case this one is missing we will use the default one specified in the class. See above.

const el = document.createElement(nodeName)

It the user passed us some content then we will add that content to the node by modifying it’s innerText property.

el.innerText = content;

Let’s not forget to return the newly created element.

return el;

Now let’s proceed to the mighty, devilish function that will delete our node. The fearless delete.

static delete(node) {
const parent = node.parentElement;
parent.removeChild(node);
}

And Voila! We finished our class. Find below the complete class and some example of some usage.

Till next time, au revoir.

Capt. V

I fly and code for fun

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store