Element

Element.prototype.replaceWith

Replaces this Element in the children list of its parent with a set of Node or string objects

Syntax

JavaScript
element.replaceWith(...nodes)

Parameters

ParameterTypeDescription
nodes...(Node | string)[]A set of Node or string objects to replace with

Return Value

undefined

Examples

Basic Usage
const old = document.querySelector('.placeholder')!
const replacement = document.createElement('div')
replacement.textContent = 'Loaded content'
old.replaceWith(replacement)
Practical Example
const skeleton = document.querySelector('.skeleton')!
skeleton.replaceWith('Content loaded successfully')
Advanced Usage
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

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.