我正在尝试从网页中删除除一个元素之外的所有元素。
首先我使用
getElementById()
找到我的元素。然后我通过 document.body.appendChild()
将它移动到身体的顶部。
如何删除其余节点,但我有这个节点?
删除元素,保存引用。删除所有其他内容。然后插入保存的元素。
var node = document.getElementById("whatever");
if (node.parentNode) {
var savedNode = node.parentNode.removeChild(node);
}
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(savedNode);
你可以先选择你的html节点,如下所示:
var selectedNode=document.getElementById("myid");
//remove it from DOM
selectedNode.parentNode.removeChild(selectedNode);
//clear the body
document.body.innerHTML = "";
//append the selectedNode
document.body.appendChild(selectedNode);
如果您要删除文档正文中的所有节点,我建议您复制所需的节点,从文档中删除所有节点,然后附加您复制的节点。例如:
test = document.body.getElementById(bla);
document.body.empty();
document.body.appendChild(test);
var remain=document.getElementById('id'),
pa=document.body;
remain=remain.parentNode.removeChild(remain);// remove and save referenced element
while(pa.lastChild) pa.removeChild(pa.lastChild); // remove all other nodes
pa.appendChild(remain); //add element to empty body
这对我有用。
只需将其粘贴到浏览器控制台(但更改目标)。
function deleteEverythingExceptThisElement(query) {
// Select the target element:
const target = document.querySelector(query);
console.log({target});
// Clear the body:
document.body.innerHTML = "";
// Reinsert the target element:
document.body.appendChild(target);
}
// Example:
deleteEverythingExceptThisElement('ul.list.ng-star-inserted');