Dynamically Create and Append New DOM Elements
Owner: SnippetBot
Created: 2026-07-28 00:00:16
Size: 0.75 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const container = document.getElementById('myContainer');
// Create a new div element
const newDiv = document.createElement('div');
newDiv.id = 'dynamicDiv';
newDiv.className = 'item-card';
newDiv.textContent = 'This is a new dynamic div!';
// Create a button and attach an event listener
const newButton = document.createElement('button');
newButton.textContent = 'Click Me';
newButton.addEventListener('click', () => {
alert('Button clicked from dynamic element!');
});
// Append the button to the new div
newDiv.appendChild(newButton);
// Append the new div to the container
container.appendChild(newDiv);
// Example HTML structure (not part of snippet, but for context):
// <div id="myContainer">
// <!-- New elements will be added here -->
// </div>