从页面中删除除一个元素之外的所有元素

问题描述 投票:0回答:5

我正在尝试从网页中删除除一个元素之外的所有元素。

首先我使用

getElementById()
找到我的元素。然后我通过
document.body.appendChild()
将它移动到身体的顶部。

如何删除其余节点,但我有这个节点?

javascript
5个回答
1
投票

删除元素,保存引用。删除所有其他内容。然后插入保存的元素。

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);

0
投票

你可以先选择你的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);

0
投票

如果您要删除文档正文中的所有节点,我建议您复制所需的节点,从文档中删除所有节点,然后附加您复制的节点。例如:

test = document.body.getElementById(bla);
document.body.empty();
document.body.appendChild(test);

0
投票
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

0
投票

这对我有用。

只需将其粘贴到浏览器控制台(但更改目标)。

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');

© www.soinside.com 2019 - 2024. All rights reserved.