The DOM Nodes Factory

Tino
2 min readMar 19, 2021
The DOM node factory, somewhere by the Black Sea in Năvodari, Romania

Creating and deleting DOM Nodes

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.

Tino

Example and source code

--

--

Tino

Software Developer and Helicopter pilot. Inventor of bubbology.