JAVASCRIPT
Dynamically Create, Style, and Append a New DOM Element
Learn how to programmatically create new HTML elements, add text content, apply CSS styles, and append them to the DOM using JavaScript.
function createAndAppendElement(parentId, tagName, textContent, styles) {
const parent = document.getElementById(parentId);
if (!parent) {
console.error(`Parent element with ID '${parentId}' not found.`);
return;
}
const newElement = document.createElement(tagName);
newElement.textContent = textContent;
if (styles) {
for (const prop in styles) {
if (styles.hasOwnProperty(prop)) {
newElement.style[prop] = styles[prop];
}
}
}
parent.appendChild(newElement);
return newElement;
}
// Example Usage:
// Assuming you have a div with id="app" in your HTML
// <div id="app"></div>
const myNewDiv = createAndAppendElement('app', 'div', 'Hello from a new div!', {
color: 'blue',
fontSize: '20px',
border: '1px solid black',
padding: '10px'
});
const myNewParagraph = createAndAppendElement('app', 'p', 'This is a dynamically added paragraph.', {
margin: '15px 0'
});
How it works: This snippet demonstrates creating a new HTML element (e.g., `div`, `p`) using `document.createElement()`. It then sets its `textContent`, applies a set of CSS styles using a loop over the `styles` object, and finally appends it to a specified parent element in the DOM using `appendChild()`. This is a core technique for building dynamic user interfaces.