Back to course

Creating New Elements: createElement()

JavaScript: The Complete '0 to Hero' Beginner Course

85. Creating New Elements: createElement()

Web applications often need to generate content dynamically, such as adding new list items or loading widgets. We use document.createElement() to create a new DOM node.

Step 1: Create the Element

javascript // Create a new <div> element const newDiv = document.createElement('div');

// Create a new <li> element const newItem = document.createElement('li');

Step 2: Configure the Element

Set its content, classes, or attributes.

javascript newDiv.id = 'dynamic-box'; newDiv.classList.add('alert'); newDiv.textContent = 'Content created by JavaScript.';

Step 3: Insert the Element (Next Lesson)

Crucially, creating an element only builds it in memory; it doesn't automatically appear on the page. You must explicitly insert it into the existing DOM tree.