← Back to all snippets
JAVASCRIPT

Dynamically Create and Append New DOM Elements

Learn how to programmatically create new HTML elements like `div` or `p`, set their attributes and content, and efficiently insert them into the DOM.

function createAndAppendElement(parentId, tagName, textContent, attributes = {}) {
  const parent = document.getElementById(parentId);
  if (!parent) {
    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]);
    }
  }

  parent.appendChild(newElement);
  return newElement;
}

// Example Usage:
const myDiv = createAndAppendElement('app-root', 'div', 'Hello World!', { id: 'my-new-div', class: 'card' });
if (myDiv) {
  createAndAppendElement('my-new-div', 'p', 'This is a dynamically added paragraph.', { class: 'text-muted' });
}
How it works: This snippet provides a reusable function to create a new HTML element, set its text content, apply a map of attributes, and then append it to an existing parent element identified by its ID. It's fundamental for building dynamic user interfaces where elements are generated based on user interaction or data fetching.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs