JAVASCRIPT
Create and Append a New HTML Element with Content
Discover how to dynamically create new HTML elements, set their text content and attributes, and append them to the DOM using JavaScript for dynamic UI generation.
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 attr in attributes) {
if (attributes.hasOwnProperty(attr)) {
newElement.setAttribute(attr, attributes[attr]);
}
}
parentElement.appendChild(newElement);
console.log(`New <${tagName}> element appended to '${parentId}'.`);
return newElement;
}
// Example Usage:
// Assuming you have an HTML element like: <div id="container"></div>
// createAndAppendElement('container', 'p', 'This is a dynamically created paragraph.', { class: 'dynamic-item', 'data-id': '123' });
// createAndAppendElement('container', 'button', 'Click Me!', { id: 'myButton', type: 'button' });
How it works: This snippet demonstrates how to programmatically create a new HTML element, assign it text content, set custom attributes, and then append it as a child to an existing parent element in the DOM. The `document.createElement()` method constructs the element, `textContent` sets its inner text, `setAttribute()` handles attributes, and `appendChild()` places it into the document structure, enabling dynamic UI generation.