Document.createElement tutorial

last modified July 10, 2020

Document.createElement tutorial shows how to create a new DOM element with Document.createElement() in JavaScript.


Document.createElement() creates a new DOM element.

After the element is created, we insert it into the document with appendChild().

Document.createElement example

The following example demonstrates the usage of the document's createElement() function.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <button id="mybtn">Create</button>
    <script src="main.js"></script>


In the example, we have a Create button which creates a new paragraph when we click on it.

const btn = document.getElementById('mybtn');
btn.addEventListener('click', generateElement);

function generateElement() {

    let el = document.createElement("p");
    el.innerText = 'A paragraph';


The JavaScript code adds an event listener to the button. The handler function creates a new element with document.createelement() and inserts a text into the element. The element is then appended to the document's body tag using appendChild() function.

In this tutorial, we have shown how to create new elements with document.createElement() function.

You might also be interested in the following related tutorials: JavaScript queryselector tutorial, Document.all tutorial, Element.classList tutorial, Element.innerHtml tutorial, Document.createNodeIterator tutorial, JQuery tutorial, Document.getElementById tutorial, or Using jQuery DatePicker.