Element.prototype.replaceWith
Replaces this Element in the children list of its parent with a set of Node or string objects
Syntax
element.replaceWith(...nodes)Parameters
| Parameter | Type | Description |
|---|---|---|
| nodes | ...(Node | string)[] | A set of Node or string objects to replace with |
Return Value
undefined
Examples
const old = document.querySelector('.placeholder')!
const replacement = document.createElement('div')
replacement.textContent = 'Loaded content'
old.replaceWith(replacement)const skeleton = document.querySelector('.skeleton')!
skeleton.replaceWith('Content loaded successfully')function upgradeElement(oldEl: Element, tag: string) {
const newEl = document.createElement(tag)
newEl.innerHTML = oldEl.innerHTML
oldEl.replaceWith(newEl)
return newEl
}Understanding Element.prototype.replaceWith
The Element.prototype.replaceWith method in JavaScript replaces this Element in the children list of its parent with a set of Node or string objects. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.
The method signature is element.replaceWith(...nodes). It accepts 1 parameter: nodes. When called, it returns undefined. Understanding when and how to use replaceWith() helps you write more expressive, readable code.
Common use cases for Element.prototype.replaceWith include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-replacechild, dom-remove, dom-before, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Element.prototype.replaceWith is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Element.prototype.replaceChildReplaces a child node within the given parent node with a new node
Element.prototype.removeRemoves the element from the DOM tree it belongs to
Element.prototype.beforeInserts a set of Node or string objects in the children list of this Element's parent, just before this Element
Element.prototype.afterInserts a set of Node or string objects in the children list of this Element's parent, just after this Element
More Element Methods
Other methods in the Element object
Related Tools
More Element Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.