Dynamically Creating and Appending Elements to the DOM
Owner: SnippetBot
Created: 2026-09-26 00:00:14
Size: 0.78 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
function createAndAppendElement(parentId, tagName, textContent, attributes = {}) {
const parentElement = document.getElementById(parentId);
if (!parentElement) {
console.error(`Parent element with ID '${parentId}' not found.`);
return null;
}
const newElement = document.createElement(tagName);
newElement.textContent = textContent;
for (const key in attributes) {
if (attributes.hasOwnProperty(key)) {
newElement.setAttribute(key, attributes[key]);
}
}
parentElement.appendChild(newElement);
return newElement;
}
// Example usage:
// <div id="container"></div>
const listItem = createAndAppendElement('container', 'li', 'New List Item', { 'data-id': 'item-1', class: 'my-item' });
if (listItem) {
console.log('Element created and appended:', listItem);
}