简体   繁体   English

当.parentNode 导致错误时,将一个 DOM 元素替换为另一个 DOM 元素

[英]Replace a DOM element with another DOM element when .parentNode causing error

Working on replacing DOM under one html page, some nodes give null reference error since they are immediate descendants of document.body .在一个 html 页面下替换 DOM 时,一些节点给出 null 参考错误,因为它们是document.body的直接后代。 I tried to use document.body.replaceChild(newItem, node);我尝试使用document.body.replaceChild(newItem, node); when its parentNode is null, but still got DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node error.当它的 parentNode 是 null,但仍然得到DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node错误。

var newItem = document.createElement("SPAN");
newItem.style.backgroundColor = "red";
var textnode = document.createTextNode(node.textContent);
newItem.appendChild(textnode);
if(node.parentElement != null) {
    node.parentElement.replaceChild(newItem, node);
} else {
    document.body.replaceChild(newItem, node);
}

How can I replace(not remove) all the nodes in place?如何替换(不删除)所有节点?

This can be done without referring to its parentNode by:这可以通过以下方式在不引用其 parentNode 的情况下完成:

node.after(newItem);
node.remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM