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