How to Dynamically Create and Append New HTML Elements
Owner: SnippetBot
Created: 2026-08-31 00:00:29
Size: 0.79 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
26
27
28
29
30
// Get a reference to an existing parent element
const parentElement = document.getElementById('container');
if (parentElement) {
// 1. Create a new div element
const newDiv = document.createElement('div');
// 2. Set its text content
newDiv.textContent = 'This is a dynamically created element!';
// 3. Add a class for styling (optional)
newDiv.classList.add('dynamic-item');
// 4. Set an attribute (e.g., a data attribute)
newDiv.setAttribute('data-id', '123');
// 5. Append the new div to the parent element
parentElement.appendChild(newDiv);
console.log('New element appended:', newDiv);
} else {
console.error('Parent element with ID "container" not found.');
}
/*
HTML structure for testing:
<div id="container">
<p>Existing content</p>
</div>
*/