HTML DOM Element replaceChild()

Example

Replace a text node in an <li> element with a new text node:

const newNode = document.createTextNode("Water");
const element = document.getElementById("myList").children[0];

element.replaceChild(newNode, element.childNodes[0]);

Before:

  • Coffee
  • Tea
  • Milk

After:

  • Water
  • Tea
  • Milk
Try it Yourself »

More examples below.


Description

The replaceChild() method replaces a child node with a new node.


Syntax

node.replaceChild(newnode, oldnode)

Parameters

Parameter Description
newnode Required.
The node to insert.
oldnode Required.
The node to remove.

Return Value

Type Description
NodeThe replaced node.


More Examples

Example

Replace an <li> element with a new <li> element:

// Create a new <li> element:
const element = document.createElement("li");

// Create a new text node:
const textNode = document.createTextNode("Water");

// Append the text node to the <li> element:
element.appendChild(textNode);

// Get the <ul> element with id="myList":
const list = document.getElementById("myList");

// Replace the first child node with the new <li> element:
list.replaceChild(element, list.childNodes[0]);

Before:

  • Coffee
  • Tea
  • Milk

After:

  • Water
  • Tea
  • Milk
Try it Yourself »

Browser Support

element.replaceChild() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.