Remove All id Attributes from nodes in a Range of Fragment

試著忘記壹切 提交于 2020-01-07 04:15:10

问题


Is there a way to remove the id attribute of every node in a range or fragment?

Update: I finally found out that the bug I'm struggling with is based on a <[script]> being included in a range, and therefore unexpectedly cloned, when a chrome user does a ctrl+a. My goal would be to remove any instance of <[script]> from the range (or doc fragment), such that it is not replicated when cloned.


回答1:


You may be able to use a TreeWalker, which works in pretty much all the browers that Range works in.

function actOnElementsInRange(range, func) {
    function isContainedInRange(el, range) {
        var elRange = range.cloneRange();
        elRange.selectNode(el);
        return range.compareBoundaryPoints(Range.START_TO_START, elRange) <= 0
                && range.compareBoundaryPoints(Range.END_TO_END, elRange) >= 0;
    }

    var rangeStartElement = range.startContainer;
    if (rangeStartElement.nodeType == 3) {
        rangeStartElement = rangeStartElement.parentNode;
    }

    var rangeEndElement = range.endContainer;
    if (rangeEndElement.nodeType == 3) {
        rangeEndElement = rangeEndElement.parentNode;
    }

    var isInRange = function(el) {
        return (el === rangeStartElement || el === rangeEndElement ||
                    isContainedInRange(el, range))
            ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
    };

    var container = range.commonAncestorContainer;
    if (container.nodeType != 1) {
        container = container.parentNode;
    }

    var walker = document.createTreeWalker(document,
        NodeFilter.SHOW_ELEMENT, isInRange, false);

    while (walker.nextNode()) {
        func(walker.currentNode);
    }
}

actOnElementsInRange(range, function(el) {
    el.removeAttribute("id");
});



回答2:


yes: http://api.jquery.com/removeAttr/



来源:https://stackoverflow.com/questions/2690122/remove-all-id-attributes-from-nodes-in-a-range-of-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!