I ma trying to write a chrome extension to replace all the specific occurrences of the text in a web page with a custom text.
I found similar questions in SO and tried the following solution but it doesn't seem to work.
config.text_config = [
{
src: "Lorem ipsum",
target: "live long and prosper"
}
]
config.text_config.forEach(function (obj) {
$('*').each(function () {
var text = $(this).text().replace(obj.src, 'REPLACEMENT_TEXT');
$(this).text(text);
})
});
Can anyone lend me a hand here?
You can do something like, in order to be sure to replace text for all nodes:
$(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'); }); }); });
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.