根据内容向 DOM 中的元素添加 class

Add class to element in the DOM based on content

***编辑——问题似乎出在我尝试添加 class 的方式上(我尝试为 class 更改一些 CSS 以进行测试它什么也没做)

我想根据文本在DOM中找到一个元素,并在其中添加一个class,这样我就可以操作it/its个父元素

这是我为此编写的函数(在此之前,我使用来自 Whosebug 的 function 遍历 DOM ,并调用我的函数来替换匹配项-(实际的字符串值现在并不重要)——我正在修改的 HTML 是 DOM。

var MATCH = ['word'];
var REPLACE = ['other'];


   function replaceText(textNode) {
    var badWord = textNode.nodeValue;
    var replaceWord = "";
    badWord.className = "filter";

    //Go through and match/replace strings equal to MATCH
    for (var i=0; i< MATCH.length; i++) {
        replaceWord = document.getElementsByClassName("filter").innerHTML;
        replaceWord = replaceWord.replace(new RegExp('\b' + MATCH[i] + '\b', 'g'), REPLACE[i]);
    }
    textNode.nodeValue = replaceWord;
}

当我像下面这样直接替换单词中的文本时它有效 - 但我想从 class 访问和修改,以便我可以更改父 elements/css

//working version without adding class
function hide(textNode) {
    var badWord = textNode.nodeValue;

    //Go through and match/replace strings equal to MATCH
    for (var i=0; i< MATCH.length; i++) {
        badWord = badWord.replace(new RegExp('\b' + MATCH[i] + '\b', 'g'), REPLACE[i]);
    }
    textNode.nodeValue = badWord;
}

来自 Whosebug 的函数 post -

walk(document.body);

function walk(node) {

    var child, next;

    switch (node.nodeType) {
        case ELEMENT:  // Element
        case DOCUMENT:  // Document
        case DOCUMENT_FRAGMENT: // Document fragment
            child = node.firstChild;
            while (child) {
                next = child.nextSibling;
                walk(child);
                child = next;
            }
            break;

        case TEXT: // Text node
            replaceText(node);
            break;
    }
}

我更改了您的 replaceText() 功能并在此页面上对其进行了测试。它替换文本并在具有替换文本的节点上添加过滤器 class。此解决方案使用 IE9 及更早版本不支持的 classList.add('filter'),但这不是问题,因为此代码用于 Chrome 扩展。

function replaceText(textNode) {
    var nodeValue = textNode.nodeValue;
    for (var i=0; i < MATCH.length; i++) {
        if(-1 != nodeValue.indexOf(MATCH[i])) {
            nodeValue = nodeValue.replace(new RegExp(MATCH[i], 'g'), REPLACE[i]);
            textNode.parentNode.classList.add('filter');
        }
    }
    textNode.nodeValue = nodeValue;
}