JAVASCRIPT
Dynamically Creating and Inserting DOM Elements
Learn how to programmatically create new HTML elements, set their attributes and text content, and insert them into the DOM using vanilla JavaScript.
// Get the container where the new element will be added
const container = document.getElementById('myContainer');
// Create a new div element
const newDiv = document.createElement('div');
// Set attributes and text content
newDiv.id = 'dynamicElement';
newDiv.className = 'info-box';
newDiv.textContent = 'This is a dynamically created element!';
newDiv.style.backgroundColor = '#e0ffe0';
newDiv.style.padding = '10px';
newDiv.style.margin = '10px 0';
newDiv.setAttribute('data-status', 'active');
// Append the new div to the container
container.appendChild(newDiv);
// To insert before another element:
// const referenceElement = document.getElementById('reference');
// container.insertBefore(newDiv, referenceElement);
// Example of HTML structure before running:
/*
<div id="myContainer">
<p>Existing content.</p>
<div id="reference">Reference element</div>
</div>
*/
How it works: This snippet demonstrates how to create a new HTML element (`div`) using `document.createElement()`. It then sets various properties like `id`, `className`, `textContent`, and inline styles, as well as a custom data attribute using `setAttribute()`. Finally, `appendChild()` is used to insert the newly created element into a specified parent container, making it visible on the webpage. It also comments on `insertBefore()` for more precise placement.