JAVASCRIPT

Replace a DOM Element with a New Element or HTML String

Understand how to replace an existing element in the DOM with a brand new element or an HTML string, providing a flexible way to update content without full re-renders.

function replaceElement(targetId, newContent, isHtmlString = false) {
    const targetElement = document.getElementById(targetId);
    if (!targetElement) {
        console.error(`Target element with ID '${targetId}' not found.`);
        return;
    }

    if (isHtmlString) {
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = newContent;
        // Replace with children of the temp div
        // If there's only one root element in newContent, replace with that.
        // If multiple, this will replace the target with all of them.
        const newElements = Array.from(tempDiv.children);
        if (newElements.length > 0) {
            targetElement.replaceWith(...newElements);
        } else {
            // If newContent was empty or just text, replace with a text node or clear.
            targetElement.replaceWith(document.createTextNode(newContent));
        }
    } else if (newContent instanceof Element) {
        targetElement.replaceWith(newContent);
    } else {
        console.error("Invalid new content provided. Must be an Element or an HTML string.");
    }
}

// Example Usage:
// Assume <p id="oldElement">This is the old content.</p>
// const newDiv = document.createElement('div');
// newDiv.textContent = 'This is the new div content.';
// newDiv.className = 'new-style';
// replaceElement('oldElement', newDiv);

// Assume <span id="anotherOld">Replace me!</span>
// replaceElement('anotherOld', '<p style="color:red;">New paragraph from HTML string!</p>', true);
How it works: This utility function provides a flexible way to replace an existing DOM element. It can accept either another DOM `Element` object or an HTML string. When an HTML string is provided, it's parsed, and its contents replace the target element, offering a powerful method for dynamic content updates and completely changing a section of the page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs