Create a New Element with JavaScript createElement | Plantpot

Create a New Element with JavaScript createElement

Web Dev
Sponsored links

In this article, I will introduce how to create a new element with JavaScript 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

Sponsored links

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