简体   繁体   中英

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 . I tried to use 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.

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:

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

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.

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