.createElement()

Anonymous contributor's avatar
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 element
const myDiv = document.createElement('div');
// Create a text node containing data
const data = document.createTextNode('Hi, Codecademy!');
// Insert the data into the div element
myDiv.appendChild(data);
// Add the element to the body
document.body.appendChild(myDiv);
}
// Call the function to add the element to the page
addElement();

The above code dynamically adds the following text to the webpage:

Hi, Codecademy!

All contributors

Contribute to Docs

Learn JavaScript on Codecademy