Friday, January 1, 2016

How to Replace all the text occurrences in the DOM with jQuery

$(function () {
  $.fn.getTextNodes = function(contentText) {
    return $(this).find(":not(iframe)").addBack().contents().filter(function() {
      return this.nodeType == 3 && this.nodeValue.indexOf(contentText) != -1;
    });
  };
  var config = {}
  config.text_config = [
    {
      src: "Lorem ipsum",
      target: "live long and prosper"
    }
  ];
  config.text_config.forEach(function (obj) {
    var re = new RegExp(obj.src, 'g');
    $('*').getTextNodes(obj.src).each(function(item, element) {
      this.nodeValue = this.nodeValue.replace(re, 'REPLACEMENT_TEXT');
    });
  });
});

html
<script src="//code.jquery.com/jquery-1.11.3.js"></script>


<div id="Message area">
    <div class="selected-div">
        Operation Lorem ipsum Lorem ipsum 1
    </div>
    <div class="selected-div">
        Operation Lorem ipsum Lorem ipsum 2
    </div>
    <div class="selected-div">
        Operation Lorem ipsum Lorem ipsum 3
    </div>
    <div class="selected-div">
        Operation Lorem ipsum Lorem ipsum4
    </div>
</div>

No comments:

Post a Comment