JAVASCRIPT
How to Create and Append New DOM Elements Dynamically
Learn to programmatically create new HTML elements like div or p, set their content and attributes, and efficiently append them to the DOM using JavaScript.
const container = document.getElementById('myContainer');
const newDiv = document.createElement('div');
newDiv.id = 'dynamicDiv';
newDiv.className = 'info-box';
newDiv.textContent = 'This is a new div created dynamically!';
newDiv.style.backgroundColor = '#e0ffe0';
newDiv.style.padding = '10px';
const newParagraph = document.createElement('p');
newParagraph.innerHTML = 'Hello, <strong>DOM Manipulation</strong>!';
container.appendChild(newDiv);
newDiv.appendChild(newParagraph);
// For multiple elements efficiently, use a DocumentFragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 3; i++) {
const item = document.createElement('li');
item.textContent = `List Item ${i + 1}`;
fragment.appendChild(item);
}
const ul = document.getElementById('myList');
if (ul) {
ul.appendChild(fragment);
}
How it works: This snippet demonstrates how to create new HTML elements using `document.createElement()`, set their attributes, content, and inline styles. It then shows appending single elements with `appendChild()`. For better performance when appending multiple elements, it illustrates using `document.createDocumentFragment()` to minimize reflows and repaints by appending all children in a single DOM operation.