← Back to all snippets
JAVASCRIPT

Dynamically Create & Append DOM Elements

Learn to dynamically create new HTML elements like div or p, set their content and attributes, and efficiently append them 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 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:
// <div id="container"></div>
const myDiv = createAndAppendElement('container', 'div', 'Hello, world!', { class: 'message', id: 'greeting' });
const myParagraph = createAndAppendElement('container', 'p', 'This is a dynamically created paragraph.', { style: 'color: blue;' });

console.log(myDiv); // The newly created div element
console.log(myParagraph); // The newly created paragraph element
How it works: This snippet provides a reusable function to dynamically create a new HTML element, set its text content, apply any specified attributes (like class or id), and append it to a designated parent element in the DOM. It leverages `document.createElement()` to create the element, `element.textContent` to set its inner text, `element.setAttribute()` to add attributes, and `parentElement.appendChild()` to attach it to the DOM tree. This is fundamental for building interactive web pages.

Need help integrating this into your project?

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

Hire DigitalCodeLabs