JAVASCRIPT
Dynamically Create and Append DOM Elements
Learn to dynamically create new HTML elements like 'div' or 'p', set their attributes and content, and append them to the DOM using JavaScript for interactive web pages.
const newDiv = document.createElement('div');
newDiv.id = 'dynamic-element';
newDiv.textContent = 'Hello, I am a new div!';
newDiv.classList.add('info-box', 'visible');
const container = document.getElementById('app-container');
if (container) {
container.appendChild(newDiv);
console.log('New div appended successfully!');
} else {
console.error('Container element not found!');
}
How it works: This snippet demonstrates how to create a new HTML element (a `div` in this case) from scratch using `document.createElement()`. It then sets various properties like `id`, `textContent`, and adds CSS classes using `classList.add()`. Finally, it finds an existing container element in the DOM and appends the newly created `div` as a child, making it visible on the webpage.