Locate every occurrence of the word 'ancient' on a webpage and substitute each one with 'modern' by utilizing a javascript bookmarklet

Is there a way to replace every occurrence of the word 'old' with 'new' on a webpage using a JS bookmarklet or greasemonkey script? I'm open to using jQuery or other frameworks if needed, as I've heard there are ways to incorporate them into both bookmarklets and greasemonkey scripts.

Answer №1

This function is designed to protect against any interference with tags or attributes, focusing solely on text content.

function safeHtmlReplace(target, replacement, element) {    
    if (!element) element = document.body;    
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            var regex = new RegExp(target, 'gi');
            nodes[n].textContent = nodes[n].textContent.replace(regex, replacement);
        } else {
            safeHtmlReplace(target, replacement, nodes[n]);
        }
    }
}

safeHtmlReplace('a', 'r');

Bookmarklet version:

javascript:function htmlreplace(a,b,element){if(!element)element=document.body;var nodes=element.childNodes;for(var n=0;n<nodes.length;n++){if(nodes[n].nodeType==Node.TEXT_NODE){nodes[n].textContent=nodes[n].textContent.replace(new RegExp(a,'gi'),b);}else{htmlreplace(a,b,nodes[n]);}}}htmlreplace('old','new');

Answer №2

If you decide to update the innerHtml, be mindful that it can potentially disrupt any dom events currently in place on the page. Consider traversing the document to modify text instead:

function replaceOldWithNew(node) {
    node = node || document.body;
    if (node.nodeType == 3) {
        // Text node
        node.nodeValue = node.nodeValue.split('old').join('new');
    } else {
        var nodes = node.childNodes;
        if (nodes) {
            var i = nodes.length;
            while (i--) replaceOldWithNew(nodes[i]);
        }
    }
}

replaceOldWithNew();

When there is no need for pattern matching, using split/join is faster than "replace". However, if pattern matching is required, utilize "replace" with a regex like this:

node.nodeValue = node.nodeValue.replace(/(?:dog|cat)(s?)/, 'buffalo$1');

To use it as a bookmarklet, here's the code snippet:

javascript:function replaceOldWithNew(node){node=node||document.body;if(node.nodeType==3){node.nodeValue=node.nodeValue.split('old').join('new');}else{var nodes=node.childNodes;if(nodes){var i=nodes.length;while(i--)replaceOldWithNew(nodes[i]);}}}replaceOldWithNew();

Answer №3

To ensure compatibility with older browsers, it is necessary to make a slight adjustment by changing Node.TEXT_NODE to 3 and updating node.textContent to node.nodeValue; the final function will appear as follows:

function replaceHTMLContent(targetString, replacementString, element) {    
    if (!element) element = document.body;    
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == 3) { //Node.TEXT_NODE == 3
            var regex = new RegExp(targetString, 'gi');
            nodes[n].nodeValue = nodes[n].nodeValue.replace(regex, replacementString);
        } else {
            replaceHTMLContent(targetString, replacementString, nodes[n]);
        }
    }
}

Answer №4

Here is a straightforward method using jQuery:

`javascript: var changeText = function(){$("body").html($("body").html().replace(/old/g,'new')); return;}; changeText();`

If you prefer to avoid jQuery, you can use the following code:

`javascript:function changeText(){document.body.innerHTML=document.body.innerHTML.replace(/old/g, "new" ); return;}; changeText();`

Remember that having the function return nothing is crucial to prevent the browser from redirecting after running the bookmarklet.

Answer №5

Here is an alternative recursive method to replace text:

function updateText(original, replacement, element){ 
  element = element || document.body; 

  var children = element.childNodes, index = 0;

  while(element = children[index]){ 
    if (element.nodeType == Node.TEXT_NODE){ 
      element.textContent = element.textContent.replace(original, replacement); 
    } else { 
      updateText(original, replacement, element); 
    } 
    index++; 
  } 
}

To make it more concise for a bookmarklet:

javascript:function updateText(o,r,e){e=e||document.body;var c=e.childNodes,i=0;while(e=c[i]){if(e.nodeType==Node.TEXT_NODE){e.textContent=e.textContent.replace(o,r);}else{updateText(o,r,e);};i++;}};updateText('original','replacement');

Answer №6

Alright, I am compiling all the valuable information that individuals are contributing into one comprehensive response.

Check out sixthgear's jQuery code below, which has been customized to be portable (sourcing jQuery from the well-known G) and condensed into a bookmarklet:

javascript:var scrEl=document.createElement('script');scrEl.setAttribute('language','javascript');scrEl.setAttribute('type','text/javascript');scrEl.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');function htmlreplace(a,b,element){if(!element)element=document.body;var nodes=$(element).contents().each(function(){if(this.nodeType==Node.TEXT_NODE){var r=new RegExp(a,'gi');this.textContent=this.textContent.replace(r,b);}else{htmlreplace(a,b,this);}};}htmlreplace('old','new');

Please note that 'old' can either be a 'string literal' or a 'reg[Ee]x'.

In my opinion, sixthgear's solution stands as the strongest answer, especially with the enhancements I have added. None of the other responses bring anything new to the table compared to this one. Using jQuery ensures exceptional cross-browser compatibility. Additionally, let's be real, I'm just too lazy for anything else. This post is community wiki, so enjoy!

Answer №7

Give this a shot! The only catch is that it will search through the entire body, so even attributes may end up getting altered.

javascript:document.body.innerHTML=document.body.innerHTML.replace( /old/g, "new" );

Answer №8

My current task involves making a slight adjustment to a script. The modification should make the script prompt for the text to search for, followed by the replacement text. Once all processing is complete, a dialog box will notify me that it's finished.

I intend to implement this on a phpmyadmin database edit page where there will be numerous textboxes filled with content (which requires searching and replacing). The search and replace texts may span multiple lines, hence I have included the 'm' parameter in the regex. Additionally, since some searches or replacements may contain HTML with quotes or double quotes, I need to account for those as well. For example:

Search for:

<img height="76" width="92" src="http://www.gifs.net/Animation11/Hobbies_and_Entertainment/Games_and_Gambling/Slot_machine.gif" /></div>
<div class="rtecenter"> <strong><em><font color="#ff0000">Vegas Baby!<br />
</font></em></strong></div>

It may be replaced with nothing (to remove the code entirely) or with other HTML. Here is the bookmarklet I have developed so far (I am not very familiar with JavaScript and bookmarklets), although it is not yet functioning in terms of finding and replacing, despite correct prompting:

javascript:var%20scrEl=document.createElement('script');scrEl.setAttribute('language','javascript');scrEl.setAttribute('type','text/javascript');scrEl.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');function%20htmlreplace(a,b,element){if(!element)element=document.body;var%20nodes=$(element).contents().each(function(){if(this.nodeType==Node.TEXT_NODE){var%20r=new%20RegExp(a,'gim');this.textContent=this.textContent.replace(r,b);}else{htmlreplace(a,b,this);alert('Done%20processing.');}});}htmlreplace(prompt('Text%20to%20find:',''),prompt('Replace%20with:',''));

If anyone has any suggestions or ideas, please share!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Which is the better choice for implementing a singleton: let or var?

I have a clear understanding of the distinction between let (locks the reference inside the block) and var (declares a variable accessible scope-wide). When it comes to implementing the singleton pattern in a module-based setting: var singleton = null; m ...

Encountered a SyntaxError on JSON Web Tokens Node JS Server: Unexpected token } found in JSON at position 24

Me, along with others, have encountered this issue: SyntaxError: Unexpected token } in JSON at position 24 at JSON.parse (<anonymous>) while following a tutorial on JSON Web Tokens (TUTORIAL LINK: https://www.youtube.com/watch?v=mbsmsi7l3r4&t=34s ...

What is the best way to access the Nodejs response object from outside the routing function?

Having an issue with obtaining a response object from outside the router function in Nodejs back-end. I can successfully log the response object in the first routing function, however, I am unable to access the values in the console of the second routing f ...

Exclusive pair of vertices within a network

I am working with a diagram that includes nodes A, B, C and several edges connecting these nodes. How can I extract the distinct pairs (A, B), (A, C), (B, C)? One potential method is: visited = []; for item1 in nodes: for item2 in nodes: if (item ...

Saving an "Online User Registry" for a messaging platform (PHP/AJAX)

In my setup, I manage multiple chat rooms by storing the list of chat users in a PHP variable. As users join or leave a room, their names are added to or removed from this list. To ensure data persistence, I rely on memcached. Periodical AJAX requests are ...

Caution: Highlighting Non-ASCII Characters in Your Django Form

Looking to implement client-side Ajax validation for my Django form. The goal is to alert users in real-time if any non-ascii characters are detected as they type in a field. Originally considered using python to check for ascii characters in the form&apo ...

Promise-based React Redux Login: An error occurred during login process

I'm currently working on my first React+Redux application and I'm still in the scaffolding phase. As a newcomer to React, I've encountered an issue with my simple login app. The AuthAction returns a Promise from the login(username, password) ...

Using routing with modules instead of components in Angular 10+ involves configuring the routing paths within the module files

I recently tried implementing modules instead of components for routing in Angular 10, but encountered a white screen issue. Any assistance would be greatly appreciated. Here is the code snippet I've been working with: import { NgModule } from &apos ...

The URL specified for the Django project could not be located when running on the httpd server

Hey there, this post may be a little lengthy but I appreciate your patience. Currently, I'm working on a Django project running on an apache2 server. In my index.html file, I have two images embedded in anchor tags: <a id="pop1" href="#"> <i ...

What is the best way to include an icon before each option in a VuetifyJS combobox?

I'm looking to enhance the combobox feature in VuetifyJS by adding an icon before each option in the dropdown menu. Can someone guide me on how to achieve this functionality? You can check out a sample of the combobox on CodePen here: https://codepen. ...

Display the input text line by line

How can I achieve the desired output for this input parameter? displayText("you and me"); expected output: ["you and me", "you and", "and me", "you", "and", "me"] I have attempted ...

What is the best way to display a variable from a function located outside of the public http folder in PHP?

I am attempting to create a registration form using Ajax. I have a script that calls a registration function located in an includes folder outside of the public html folder. The output of this function should be alerted, but when I click the button, the al ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

Tips for overriding the jQuery autocomplete menu item menuFocus event function

I am searching for a way to customize the behavior of the "menufocus" event triggered by arrow key navigation on items. // Here is an extension to enhance autocomplete functionality // The problem is that the default jQuery UI autocomplete menufocus is ...

Using Angular Material for creating tabs with identical content

I am using material with angularjs and have encountered an issue with my two md-tabs. Both tabs have a similar DOM structure, but contain some unique content. Instead of duplicating the common DOM twice, I am looking for an alternative solution. Is it poss ...

Creating a half drop and half brick pattern on canvas is a fun and easy way to add

I have successfully created an image using canvas https://i.sstatic.net/AIvSH.png Now I am looking to create a similar image using canvas https://i.sstatic.net/y8kGt.png I have included the code I have worked on so far. <div id="canvas_div" style=" ...

How can you handle events on DOM elements that haven't been created yet in JavaScript?

In my JavaScript module, I have the following code: EntryController = function$entry(args) { MainView(); $('#target').click(function() { alert('Handler called!'); }); } The MainView() function includes a callback ...

implementing jqBarGraph on my webpage

Hey there! I have been trying to add a graph to my HTML page for quite some time now. After doing some research, I discovered that using the jqBarGraph plug-in makes it easier to create the desired graph. Below you will find the code that I have on my webp ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

Transmitting checkbox selections using Ajax

Here is the original code that I have written. It attempts to post the value of an input for each checked checkbox. <tbody class="myFormSaldo"> <tr> <td> <input name="checkbox['.$i.']" type="chec ...