JAVASCRIPT
Create and Append New HTML Elements to the DOM
Learn how to dynamically create new HTML elements like `div` or `p`, set their text content and attributes, and efficiently append them to an existing parent element in the DOM.
function createAndAppendElement(parentElementId, tagName, textContent, attributes = {}) {
const parentElement = document.getElementById(parentElementId);
if (!parentElement) {
console.error(`Parent element with ID "${parentElementId}" not found.`);
return;
}
const newElement = document.createElement(tagName);
newElement.textContent = textContent;
for (const key in attributes) {
if (Object.hasOwnProperty.call(attributes, key)) {
newElement.setAttribute(key, attributes[key]);
}
}
parentElement.appendChild(newElement);
return newElement;
}
// Usage example:
// <div id="app"></div>
// const myDiv = createAndAppendElement('app', 'div', 'Hello World!', { id: 'myDiv', class: 'message' });
// createAndAppendElement('myDiv', 'p', 'This is a paragraph inside the div.');
How it works: This function dynamically creates a new HTML element of a specified tag name, assigns its text content, applies any custom attributes, and then appends it as a child to a designated parent element identified by its ID. This is a fundamental operation for building and updating user interfaces programmatically.