什么时候是“;“安全”;以在解析文档时修改给定的html元素/节点

When is it "safe" to modify a given html element/node while parsing the document?

本文关键字:修改 元素 节点 html 安全 什么时候 文档      更新时间:2023-09-26

在解析和修改HTML页面时,我只想更改文本内容,不想触摸scriptstyle标签(肯定会有更多我不想惹的东西)。

除了显式检查nodeName != "SCRIPT"之外,有没有一种干净的方法可以只解析和修改html页面上的文本?

如果您想更改除scriptstyle标记之外的内容,检查它们听起来非常合理。

node.nodeName != 'SCRIPT' && node.nodeName != 'STYLE'

如果您试图遍历DOM并只检查/修改显示的文本,那么您需要对一堆标记类型进行特殊处理,避免介入或修改它们。该列表中有:<script><iframe><object><embed><style>

如果你感兴趣的话,这里有一个我使用过的树遍历函数,它跳过了这些标签,并经过了一些性能优化,比递归实现工作得更快。这可能不是您想要的确切函数,但您可以获得跳过标记的大致想法。这可以通过一个小的更改来调整,只在文本节点上调用回调:

var treeWalkFast = (function() {
    // create closure for constants
    var skipTags = {"SCRIPT": true, "IFRAME": true, "OBJECT": true, "EMBED": true, "STYLE": true};
    return function(parent, fn, allNodes) {
        var node = parent.firstChild, nextNode;
        while (node && node != parent) {
            if (allNodes || node.nodeType === 1) {
                if (fn(node) === false) {
                    return(false);
                }
            }
            // if it's an element &&
            //    has children &&
            //    has a tagname && is not in the skipTags list
            //  then, we can enumerate children
            if (node.nodeType === 1 && node.firstChild && !(node.tagName && skipTags[node.tagName])) {
                node = node.firstChild;
            } else  if (node.nextSibling) {
                node = node.nextSibling;
            } else {
                // no child and no nextsibling
                // find parent that has a nextSibling
                while ((node = node.parentNode) != parent) {
                    if (node.nextSibling) {
                        node = node.nextSibling;
                        break;
                    }
                }
            }
        }
    }
})();

与其检查nodeName != "SCRIPT",不如只查询所需的元素,并使用document.getElementsByNamedocument.getElementsByTagName,。。。如果使用像jQuery这样的库,那么只查询需要修改的元素应该是一项简单的任务。