JAVASCRIPT
Dynamically Creating and Appending New DOM Elements
Learn how to programmatically create new HTML elements, set their attributes, and append them to the DOM using JavaScript, essential for dynamic content generation.
const newDiv = document.createElement('div');
newDiv.id = 'myNewElement';
newDiv.className = 'info-box';
newDiv.textContent = 'This is a dynamically created element!';
// Add some inline style for visibility (optional)
newDiv.style.backgroundColor = '#e0f7fa';
newDiv.style.padding = '15px';
newDiv.style.margin = '10px';
newDiv.style.border = '1px solid #00bcd4';
document.body.appendChild(newDiv);
console.log('New element appended to body.');
How it works: This snippet demonstrates creating a new 'div' element using `document.createElement()`. It then assigns an ID, a CSS class, and sets its text content. Optionally, basic inline styles are added for immediate visual feedback. Finally, the newly created element is appended as a child to the 'body' of the document, making it visible on the page.