How to replace text in html document without affecting the markup?

后端 未结 2 1490
清歌不尽
清歌不尽 2020-12-09 23:55

How can I write a javascript/jquery function that replaces text in the html document without affecting the markup, only the text content?

For instance if I want to r

相关标签:
2条回答
  • 2020-12-10 00:01

    Use the :contains selector to find elements with matching text and then replace their text.

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

    Unfortunately you can't use text() for this as it strips out HTML from all descendant nodes, not just child nodes and the replacement won't work as expected.

    0 讨论(0)
  • 2020-12-10 00:05

    You will have to look for the text nodes on your document, I use a recursive function like this:

    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++; 
      } 
    }
    

    If you do it in that way, your markup and event handlers will remain intact.

    Edit: Changed code to support IE, since the textnodes on IE don't have a textContent property, in IE you should use the nodeValue property and it also doesn't implements the Node interface.

    Check an example here.

    0 讨论(0)
提交回复
热议问题