JAVASCRIPT
Create and Append New DOM Elements
Discover how to programmatically create new HTML elements and append them to an existing parent element in the DOM using createElement and appendChild.
const newDiv = document.createElement('div');
newDiv.textContent = 'This is a dynamically created div!';
newDiv.id = 'dynamic-content';
newDiv.classList.add('info-box');
const newParagraph = document.createElement('p');
newParagraph.innerHTML = 'Learn more <a href="#">here</a>.';
// Append the paragraph to the div
newDiv.appendChild(newParagraph);
// Find an existing container element in the DOM
const container = document.getElementById('main-container');
// Append the new div (with its child paragraph) to the container
if (container) {
container.appendChild(newDiv);
} else {
console.error('Container element not found.');
}
How it works: This code illustrates how to build new DOM elements from scratch. `document.createElement()` creates a new HTML tag. You can then set its `textContent` or `innerHTML`, add `id`s and `classList`s. Child elements are attached using `appendChild()`. Finally, the entire new element structure is added to an existing part of the webpage, making it visible to the user.