如何在不影响标记的情况下替换html文档中的文本?

时间:2009-10-03 05:21:06

标签: javascript jquery regex

如何编写一个javascript / jquery函数来替换html文档中的文本而不影响标记,只影响文本内容?

例如,如果我想在这里用“no style”替换“style”这个词:

<tr>
<td style="width:300px">This TD has style</td>
<td style="width:300px">This TD has <span class="style100">style</span> too</td>
</tr>

我不希望替换影响标记,只影响用户可见的文本内容。

2 个答案:

答案 0 :(得分:13)

您必须在文档中查找文本节点,我使用这样的递归函数:

function replaceText(oldText, newText, node){ 
  node = node || document.body; // base node 

  var childs = node.childNodes, i = 0;

  while(node = childs[i]){ 
    if (node.nodeType == 3){ // text node found, do the replacement
      if (node.textContent) {
        node.textContent = node.textContent.replace(oldText, newText);
      } else { // support to IE
        node.nodeValue = node.nodeValue.replace(oldText, newText);
      }
    } else { // not a text mode, look forward
      replaceText(oldText, newText, node); 
    } 
    i++; 
  } 
}

如果以这种方式执行此操作,您的标记和事件处理程序将保持不变。

编辑:更改了代码以支持IE,因为IE上的文本节点没有textContent属性,在IE中你应该使用nodeValue属性,它也是没有实现Node接口。

查看示例here

答案 1 :(得分:4)

使用:contains选择器查找具有匹配文字的元素,然后替换其文本。

$(":contains(style)").each(function() {
  for (node in this.childNodes) {
    if (node.nodeType == 3) { // text node
      node.textContent = node.textContent.replace("style", "no style");
    }
  }
});

不幸的是,您无法使用text(),因为它从所有后代节点中剥离HTML,而不仅仅是子节点,并且替换将无法按预期工作。