我有一个嵌套了很多div的网页。如何删除除具有特定ID及其子项的1之外的所有元素。
我希望保留那个div及其子女,并删除其他所有内容甚至其父母
以下代码无法正常删除子代
var elms = document.getElementsByTagName('*');
for (var i = 0; i < elms.length; i++) {
if (elms[i].id != "div63") {
elms[i].parentNode.removeChild(elms[i])
}
};
我想要一个非jQuery解决方案。
答案 0 :(得分:3)
您可以保存对节点的引用,删除所有引用,然后将节点放在正文中:
var saved = document.getElementById('div63');
var elms = document.body.childNodes;
while (elms.length) document.body.removeChild(elms[0]);
document.body.appendChild(saved);
答案 1 :(得分:1)
由dystroy提供的轻微替代方法,其中以下内容移动您希望保留的元素,将其作为您想要的父级的第一个子级删除所有其他子项(如果没有提供父项,则默认为body
元素),而不是替换“删除所有内容然后将其放回”方法。移动之后,这将删除该父级的所有后续子节点(这包括一个相当丑陋的函数来检索给定元素,尽管没有尝试补偿{{1}的缺失在没有该功能的浏览器中)):
document.querySelector()
可以使用CSS选择器字符串,如上所述调用它,或者如下所示:
function retrieveElem(ref) {
if (!ref) {
return document.body;
} else {
if (typeof ref === 'string') {
if (document.querySelector) {
var dQSresult = document.querySelector(ref);
if (dQSresult) {
return dQSresult;
} else {
return document.querySelector('#' + ref);
}
}
} else {
switch (ref.nodeType) {
case 1:
// it's an element
return ref;
case 9:
// it's the document node
return document.body;
}
}
}
}
function clearAllExcept(el, from) {
el = retrieveElem(el);
from = retrieveElem(from);
from.insertBefore(el, from.firstChild);
while (from.firstChild.nextSibling) {
from.removeChild(from.firstChild.nextSibling);
}
}
clearAllExcept('#id63','.aChild');
// with a CSS selector to identify the `id` of the child
clearAllExcept('#id63');
// with a string to identify the `id` of the child
clearAllExcept('id63');
类似的选择器可用于识别父级,也包括:
// with a node-reference to the child:
clearAllExcept(document.getElementById('id63'));
// using the `document`:
clearAllExcept('#id63', document);
// with a string to identify the `id` of the parent
clearAllExcept('#id63','#test');
参考文献: