← Back to all snippets
JAVASCRIPT

Replacing One DOM Element with Another

Learn to replace an existing HTML element in the DOM with a completely new one using `Node.replaceChild()`, enabling dynamic content updates without full re-renders.

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

  const newElement = document.createElement(newTagName);
  newElement.textContent = newTextContent;

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

  oldElement.parentNode.replaceChild(newElement, oldElement);
  return newElement;
}

// Usage example:
// <p id="oldParagraph">This is the original paragraph.</p>
// replaceElement('oldParagraph', 'h2', 'This is the new heading!', { class: 'highlight' });
How it works: This snippet demonstrates how to replace an existing element in the DOM with a brand new one. It first identifies the `oldElement` and creates a `newElement` with specified tag, text, and attributes. Then, `oldElement.parentNode.replaceChild(newElement, oldElement)` is called, which efficiently swaps the elements, updating the UI. This is useful for dynamic content changes where an element's type or entire content needs to be altered.

Need help integrating this into your project?

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

Hire DigitalCodeLabs