.createElement()
Anonymous contributor
Published Mar 8, 2025
Contribute to Docs
In JavaScript, the .createElement()
method of the document
object creates a new element node of the specified type. This method returns an HTMLElement
instance, which can be modified and appended to the DOM.
Syntax
document.createElement(type)
type
: A string representing the tag name of the element to be created.
Example
The following example demonstrates the usage of the .createElement()
method:
function addElement() {// Create a div elementconst myDiv = document.createElement('div');// Create a text node containing dataconst data = document.createTextNode('Hi, Codecademy!');// Insert the data into the div elementmyDiv.appendChild(data);// Add the element to the bodydocument.body.appendChild(myDiv);}// Call the function to add the element to the pageaddElement();
The above code dynamically adds the following text to the webpage:
Hi, Codecademy!
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours