Creating DOM elements using Javascript and adding them to the DOM is a very common task. In this article, I’ll go over two ways to do it.
insertAdjacentHTML Method
The first method to add an element to the DOM is the insertAdjacentHTML method. This method is available on all DOM elements in JavaScript and look like this:
existingElement.insertAdjacentHTML(‘beforeend’ , ‘<p>New Element</p>’);
Note that in this example, existingElement is a DOM element that is already selected in the code.
It takes two arguments. The first argument is a string that specifies the relative position of the new element to the existing element and it can have one of these four values:
- beforebegin
Before the opening tag of the existing element. - afterbegin
Just after the opening tag of the existing element, before its first child. - beforeend
Just before the closing tag of the element, after its last child. - afterend
After the closing tag of the element.
The second argument is also a string. This string will be parsed as HTML and inserted into the DOM in the specified position.
document.createElement() Method
The second way of creating and adding elements into the DOM is to first create them using the document.createElement() method, and then insert them into an element using the append() or prepend() methods. The process is like this:
First, we create the element in JavaScript. For instance to create a div element we write:
let myDiv = document.createElement(“div”)
Note that in this stage myDiv is only a DOM element in JavaScript and it doesn’t exist in the DOM yet. Before inserting it into the DOM we have the option to modify its class, id or text content.
myDiv.classList.add(‘box’)
myDiv.id = ‘box1’
myDiv.textContent = ‘This is a box!’
The element still isn’t in the DOM. To finally insert it into the DOM, we can use the append or prepend methods on an existing element.
existingElement.append(myDiv)
or
existingElement.prepend(myDiv)
The append method inserts the new element after the last child of the existing element. (kinda similar to insertAdjacentHTML with beforeend argument.)
On the other hand, the prepend method inserts the new element before the first child of the existing element. (kinda similar to insertAdjacentHTML with afterbegin argument.)
And this was how to add DOM elements using JavaScript in a nutshell.