← Back to all snippets
JAVASCRIPT

Dynamically Creating and Appending a New DOM Element

Learn how to create a new HTML element, set its text content and attributes, and efficiently append it to an existing parent element in the DOM using JavaScript.

function createAndAppendElement(parentId, tagName, textContent, attributes) {
  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;

  for (const key in attributes) {
    if (attributes.hasOwnProperty(key)) {
      newElement.setAttribute(key, attributes[key]);
    }
  }

  parent.appendChild(newElement);
  return newElement;
}

// Usage example:
// <div id="container"></div>
// createAndAppendElement('container', 'p', 'This is a dynamically created paragraph!', { id: 'dynamic-p', class: 'info' });
How it works: This snippet demonstrates how to programmatically create a new HTML element using `document.createElement()`, set its `textContent`, and add multiple attributes using `setAttribute()`. Finally, `appendChild()` is used to insert the new element into a specified parent element in the DOM. This is a fundamental operation for rendering dynamic UI components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs