JavaScript:在textNode中添加元素

tho*_*mas 12 html javascript replace textnode

我想在textNode中添加一个元素.例如:我有一个函数,用于在元素的textNode中搜索字符串.当我找到它时,我想用HTML元素替换.那有什么标准吗?谢谢.

pal*_*wim 19

您不能只替换字符串,您必须替换整个TextNode元素,因为TextNode元素不能包含 DOM中的子元素.

因此,当您找到文本节点时,生成替换元素,然后使用类似于以下的函数替换文本节点:

function ReplaceNode(textNode, eNode) {
    var pNode = textNode.parentNode;
    pNode.replaceChild(textNode, eNode);
}
Run Code Online (Sandbox Code Playgroud)

For what it appears you want to do, you will have to break apart the current Text Node into two new Text Nodes and a new HTML element. Here's some sample code to point you hopefully in the right direction:

function DecorateText(str) {
    var e = document.createElement("span");
    e.style.color = "#ff0000";
    e.appendChild(document.createTextNode(str));
    return e;
}

function SearchAndReplaceElement(elem) {
    for(var i = elem.childNodes.length; i--;) {
        var childNode = elem.childNodes[i];
        if(childNode.nodeType == 3) { // 3 => a Text Node
            var strSrc = childNode.nodeValue; // for Text Nodes, the nodeValue property contains the text
            var strSearch = "Special String";
            var pos = strSrc.indexOf(strSearch);

            if(pos >= 0) {
                var fragment = document.createDocumentFragment();

                if(pos > 0)
                    fragment.appendChild(document.createTextNode(strSrc.substr(0, pos)));

                fragment.appendChild(DecorateText(strSearch));

                if((pos + strSearch.length + 1) < strSrc.length)
                    fragment.appendChild(document.createTextNode(strSrc.substr(pos + strSearch.length + 1)));

                elem.replaceChild(fragment, childNode);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Maybe jQuery would have made this easier, but it's good to understand why all of this stuff works the way it does.