Ebooks

Document.createElement tutorial

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 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.