Create a New Element with JavaScript createElement

01/18/2022

Contents

In this article, you will learn how to create a new element with JavaScript createElement.

createElement()

The createElement () method is a method that can create a new element by specifying the name of the tag as an argument.

If the tag specified in the argument does not exist, “HTMLUnknownElement” is returned.

Below is a sample to create a p element

document.createElement("p");

Create a new element with createElement

The following is a sample that first creates a p element with createElement, adds attributes and text to it, and adds it inside the body element.

//Create the p element
const el = document.createElement("p");
//add the id attribute
el.setAttribute("id", "paragraph");
//add the text
el.textContent = "Hello World!";
//add the p element inside the body element
document.body.appendChild(el);