Skip to main content Accessibility Feedback

DOM Injection

Element.replaceWith()

Replace an element (and all of its HTML elements and content) with another. Call the Element.replaceWith() method on the target node, and pass in one or more elements or strings as arguments.

<h1>Good evening</h1>
// Get the target element
let h1 = document.querySelector('h1');

// Create a new element
let p = document.createElement('p');
p.textContent = 'Good morning';

// Replace the target with the new element
// <p>Good morning</p>
h1.replaceWith(p);

// You can replace it with more than one item by passing in multiple arguments
// <p>Good morning</p>How are you today?
h1.replaceWith(p, 'How are you today?');

Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.


Find this useful? You can support my work by purchasing an annual membership.