Document.createElement tutorial shows how to create a new DOM element with Document.createElement() in JavaScript.
last modified August 24, 2023
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.
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.
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.