Creating and inserting elements in JavaScript

Now we will learn how to create new DOM elements through JavaScript, and then add them to the page. The createElement method is designed for this aim. Name of the tag to be created should be passed as the parameter of this method.

If we write the result of createElement into a variable, then this variable will contain such an element as if we got it through querySelector.

The only difference is that our element will not be placed on the page. And so we can change its text, attributes, hang event handlers and eventually place it on the page.

The appendChild method is used to place a new element on the page. This method should be applied to the element in which we want to place our element. And our new element created earlier through createElement should be passed as the method parameter.

Let's look at a practical example. Suppose we have a div and a few paragraphs in it:

<div id="parent"> <p>1</p> <p>2</p> <p>3</p> </div>

Let's create a paragraph, set the text for it and place it on the page at the end of the #parent block:

let parent = document.querySelector('#parent'); let p = document.createElement('p'); p.textContent = '!'; parent.appendChild(p);

Result of code execution:

<div id="parent"> <p>1</p> <p>2</p> <p>3</p> <p>!</p> </div>

Given an ol:

<ol id="elem"></ol>

Insert a li at the end of it with the text 'item'.

Given an ol and a button:

<ol id="elem"></ol> <button id="button">click me</button>

Make it so that when you click on the button, a li is added to the end of the list with the text 'item'.