JAVASCRIPT

Replace a DOM Element with a New One

Understand how to replace an existing HTML element in the DOM with a brand new or pre-existing element using `replaceWith()` for seamless UI updates and content changes.

function replaceElementWithNewContent(oldElementId, newElementType, newTextContent) {
  const oldElement = document.getElementById(oldElementId);
  if (!oldElement) {
    console.error(`Old element with ID '${oldElementId}' not found.`);
    return;
  }

  const newElement = document.createElement(newElementType);
  newElement.textContent = newTextContent;
  newElement.className = 'replaced-content'; // Optional: add a class for styling

  // Replace the old element with the new one
  oldElement.replaceWith(newElement);
  console.log(`Element '${oldElementId}' replaced with a new '${newElementType}' element.`);
}

// Example Usage:
// Assume an HTML paragraph: <p id="message">Original message here.</p>
replaceElementWithNewContent('message', 'div', 'This is the new content in a div!');
How it works: This code snippet illustrates how to replace one DOM element with another using the `replaceWith()` method. This method allows you to swap an existing element in the DOM with a new element (either newly created or another existing element from the DOM). It's a clean and direct way to update parts of your UI, such as replacing a loading spinner with actual content, or changing the type of an element while preserving its position in the DOM tree. The original element is effectively removed, and the new one takes its place.

Need help integrating this into your project?

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

Hire DigitalCodeLabs