JAVASCRIPT
Dynamically Creating and Appending a New Element
Learn how to programmatically create new HTML elements, set their attributes and text content, and append them to the DOM using vanilla JavaScript.
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) {
newElement.setAttribute(key, attributes[key]);
}
parentElement.appendChild(newElement);
return newElement;
}
// Example usage:
// Assume a div with id="app-container" exists in your HTML
// <div id="app-container"></div>
const myButton = createAndAppendElement(
'app-container',
'button',
'Click Me!',
{ id: 'my-dynamic-button', class: 'btn btn-primary' }
);
if (myButton) {
myButton.addEventListener('click', () => {
alert('Button clicked!');
});
}
const myParagraph = createAndAppendElement(
'app-container',
'p',
'This is a dynamically created paragraph.',
{ class: 'info-text' }
);
How it works: This snippet demonstrates how to create a new HTML element (e.g., `button`, `p`) using `document.createElement()`. It then sets its text content with `textContent` and adds any specified attributes using `setAttribute()`. Finally, the `appendChild()` method inserts the newly created element into the DOM as a child of a specified parent element, providing a fundamental way to build dynamic web interfaces.