ZetCode

Document.createElement tutorial

last modified August 24, 2023

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

Document.createElement

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.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document.createElement</title>
</head>
<body>

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

</body>
</html>

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

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

function generateElement() {

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

    document.body.appendChild(el);
}

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 article we have shown how to create new elements with document.createElement function.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.