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, ie 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.
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>
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.