JAVASCRIPT

Dynamically Create and Append an HTML Element

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

function createAndAppendElement(parentId, tagName, textContent) {
  const parentElement = document.getElementById(parentId);
  if (parentElement) {
    const newElement = document.createElement(tagName);
    newElement.textContent = textContent;
    parentElement.appendChild(newElement);
    return newElement;
  }
  return null;
}

// Example Usage:
// Assume you have a div with id="container" in your HTML
// <div id="container"></div>

// createAndAppendElement('container', 'p', 'This is a new paragraph added dynamically!');
// createAndAppendElement('container', 'h3', 'Dynamic Heading');
How it works: This snippet demonstrates how to create a new HTML element (e.g., 'p', 'div', 'h3') using `document.createElement()`, set its text content with `textContent`, and then attach it to a specified parent element in the DOM using `appendChild()`. It's a foundational skill for building dynamic UIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs