替换元素中字符串的所有ocurrance [英] Replace all the ocurrance of a string in an element

查看:265
本文介绍了替换元素中字符串的所有ocurrance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换给定元素的所有后代元素中的特定字符串。

I want to replace a particular string in (the text of) all the descendant elements of a given element.

innerHTML 不能使用,因为这个序列可以出现在属性中。我已经尝试使用XPath,但它似乎接口本质上是只读的。因为这仅限于一个元素,所以不能使用像 document.getElementsByTagName 这样的功能。

innerHTML cannot be used as this sequence can appear in attributes. I have tried using XPath, but it seems the interface is essentially read-only. Because this is limited to one element, functions like document.getElementsByTagName cannot be used either.

有任何建议这样做吗?任何jQuery或纯DOM方法都是可以接受的。

Could any suggest any way to do this? Any jQuery or pure DOM method is acceptable.

编辑:

正在努力解决:直接在元素上修改文本将导致所有非Text子节点被删除。

Some of the answers are suggesting the problem I was trying to work around: modifying the text directly on an Element will cause all non-Text child nodes to be removed.

所以问题本质上归结于如何有效地选择树中的所有文本节点。在XPath中,您可以轻松地将其作为 // text()执行,但是当前的XPath界面不允许您更改这些文本节点似乎。

So the problem essentially comes down to how to efficiently select all the Text nodes in a tree. In XPath, you can easily do it as //text(), but the current XPath interface does not allow you to change these Text nodes it seems.

执行此操作的一种方法是按照Bergi的回答所示递归。另一个方式是使用 find('*') selector的jQuery,但这有点贵。仍然在等待看是否有更好的解决方案。

One way to do this is by recursion as shown in the answer by Bergi. Another way is to use the find('*') selector of jQuery, but this is a bit more expensive. Still waiting to see if there' are better solutions.

推荐答案

只需使用一个简单的自制DOM迭代器,节点:

Just use a simple selfmade DOM-iterator, which walks recursively over all nodes:

(function iterate_node(node) {
    if (node.nodeType === 3) { // Node.TEXT_NODE
        var text = node.data.replace(/any regular expression/g, "any replacement");
        if (text != node.data) // there's a Safari bug
            node.data = text;
    } else if (node.nodeType === 1) { // Node.ELEMENT_NODE
        for (var i = 0; i < node.childNodes.length; i++) {
            iterate_node(node.childNodes[i]); // run recursive on DOM
        }
    }
})(content); // any dom node

这篇关于替换元素中字符串的所有ocurrance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆