Robert C. Holland
Robert C. Holland

Reputation: 1813

How to replace a DOM element with another?

If I have a existing elementA on page and I use document.createElement(...) to create elementB. elementA and elementB are not the same type of tag (eg. h1 and iframe, i.e. can't use innerHTML), how can I replace elementA with elementB without using jQuery ?

What I've tried (insert new before + remove old):

elementA.insertBefore(elementB, elementA.firstChild);
elementA.parentNode.removeChild(elementA)

Above doesn't work as elementB is being inserted as a child of elementA and removing elementA after that removes both.

Upvotes: 0

Views: 2713

Answers (2)

Pineda
Pineda

Reputation: 7593

Looks like you want to replace a parent element elementA with elementB so that elementB has the first child of elementA.

One way of achieving the latter is as follows:

// Append `elementB` to `elementA.parentNode` first:
elementA.parentNode.appendChild(elementB)

// Append `elementA.firstchild` to `elementB`:
elementB.parentNode.appendChild(elementA.firstChild)

// Remove `elementA`:
elementA.parentNode.removeChild(elementA)

Upvotes: 2

Eduen Sarceño
Eduen Sarceño

Reputation: 130

You can use node.replaceChild

The Node.replaceChild() method replaces one child node of the specified node with another.

replacedNode = parentNode.replaceChild(newChild, oldChild);
  • newChild is the new node to replace oldChild. If it already exists in the DOM, it is first removed.
  • oldChild is the existing child to be replaced.
  • replacedNode is the replaced node. This is the same node as oldChild.

var a = document.getElementById('A')
var h = document.createElement('h1')
h.appendChild(document.createTextNode('Title h1'))
a.replaceChild(h, a.firstChild)
<div id="A"><p>Paragraph A</p></div>

Upvotes: 3

Related Questions