JAVASCRIPT
Creating and Appending New DOM Elements
Learn how to programmatically create a new HTML element, add content and classes, and append it to an existing parent element using JavaScript DOM methods.
// Create a new div element
const newDiv = document.createElement('div');
// Add some content to the div
newDiv.textContent = 'Hello, I am a new dynamically created element!';
// Add a class for styling (optional)
newDiv.classList.add('dynamic-content');
// Get a reference to an existing parent element
const parentElement = document.getElementById('container'); // Assuming an element with id="container" exists
// Append the new div to the parent element
if (parentElement) {
parentElement.appendChild(newDiv);
} else {
console.error('Parent element with ID "container" not found.');
}
How it works: This snippet demonstrates how to dynamically create a new HTML element (a 'div' in this case) using `document.createElement()`. It then assigns text content and adds a CSS class for styling. Finally, it locates an existing parent element by its ID and appends the newly created element to it, making it part of the live DOM.