HTML DOM Element replaceChild() method

Definition and usage

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

See also:

removeChild() method

remove() method

appendChild() method

insertBefore() method

childNodes property

firstChild property

lastChild property

firstElementChild property

lastElementChild property

Related document methods:

createElement() method

createTextNode() method

Instance

Example 1

Replace the text node within the <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]);

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

  • Before replacement:
  • Tea
  • Milk

After replacement:

  • Water
  • Tea
  • Milk

Try It Yourself

Example 2

Replace the <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");
// Get the <ul> element with id="myList":
// Replace the first child node with a new <li> element:

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

  • Before replacement:
  • Tea
  • Milk

After replacement:

  • Water
  • Tea
  • Milk

Try It Yourself

Syntax

node.replaceChild(newnode, oldnode)

Parameter

Parameter Description
newnode Required. The node to be inserted.
oldnode Required. The node to be deleted.

Return Value

Type Description
Node Object The replaced node.

Browser Support

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

All browsers fully support it:

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