如何解析文档并删除除与ID及其子元素匹配的元素外的所有元素?

How can I parse a document and remove all elements except for one that matches and ID and its children

本文关键字:元素 文档 何解析 删除 ID      更新时间:2023-09-26

我有一个网页与许多div嵌套。如何删除除1以外的具有特定ID及其子元素的所有元素?

我想保留这个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解决方案

您可以保存对节点的引用,删除所有引用,然后将节点放在body中:

var saved = document.getElementById('div63');
var elms = document.body.childNodes;
while (elms.length) document.body.removeChild(elms[0]);
document.body.appendChild(saved);
演示

一种稍微替代方法,与dystroy提供的方法相比,下面移动您希望保留的元素,将其放置为父元素的第一个子元素,您希望从该父元素中删除所有其他子元素(如果没有提供父元素,默认为body元素),而不是替代的"删除所有内容然后将其放回"方法。在移动之后,这将从该父节点中删除所有后续子节点(这包括一个相当丑陋的函数来检索给定元素,尽管没有尝试补偿没有该功能的浏览器中缺乏document.querySelector())):

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

JS Fiddle demo.

这可以像上面那样调用,使用CSS选择器字符串,或者如下:

// with a CSS selector to identify the `id` of the child
clearAllExcept('#id63');

JS Fiddle demo.

// with a string to identify the `id` of the child
clearAllExcept('id63');

JS Fiddle demo.

// with a node-reference to the child:
clearAllExcept(document.getElementById('id63'));

JS Fiddle demo.

类似的选择器也可以用来标识父元素:

// using the `document`:
clearAllExcept('#id63', document);

JS Fiddle demo.

// with a string to identify the `id` of the parent
clearAllExcept('#id63','#test');

JS Fiddle demo.

// with a node-reference to the parent:
clearAllExcept('#id63', document.getElementById('test'));

JS Fiddle demo.

引用:

  • document.querySelector() .
  • Node.firstChild .
  • Node.insertBefore .
  • Node.nextSibling .
  • Node.nodeType .
  • switch () .