[英]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并且使用
document.createElement(...)
创建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 ? elementA和elementB不是同一类型的标记(例如h1和iframe,即不能使用innerHTML),如何在不使用jQuery的情况下用elementB替换elementA?
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. 上面的方法不起作用,因为elementB作为elementA的子元素插入,并且在删除这两个元素之后都将其删除。
You can use node.replaceChild
您可以使用
node.replaceChild
The Node.replaceChild() method replaces one child node of the specified node with another.
Node.replaceChild()方法将指定节点的一个子节点替换为另一个子节点。
replacedNode = parentNode.replaceChild(newChild, oldChild);
- newChild is the new node to replace oldChild.
newChild是替换oldChild的新节点。 If it already exists in the DOM, it is first removed.
如果它已经存在于DOM中,则首先将其删除。
- oldChild is the existing child to be replaced.
oldChild是要替换的现有子级。
- replacedNode is the replaced node.
replaceNode是替换的节点。 This is the same node as oldChild.
这是与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
. 看起来您想用
elementB
替换父元素elementA
,以便elementB
具有elementA
的第一个子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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.