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
element
const newDiv = document.createElement('div');
element
const newItem = document.createElement('li');
// Create a new
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.