繁体   English   中英

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

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

我有一个嵌套了很多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解决方案。

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

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小提琴演示

这可以使用CSS选择器字符串如上所述调用,或者如下所示:

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

JS小提琴演示

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

JS小提琴演示

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

JS小提琴演示

类似的选择器也可用于识别父级,也是:

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

JS小提琴演示

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

JS小提琴演示

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

JS小提琴演示

参考文献:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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