Can the JavaScript command .replace replace text in any webpage? I want to create a Chrome extension that replaces specific words in any webpage to say something else (example cake instead of pie).
Advertisement
Answer
The .replace
method is a string operation, so it’s not immediately simple to run the operation on HTML documents, which are composed of DOM Node objects.
Use TreeWalker API
The best way to go through every node in a DOM and replace text in it is to use the document.createTreeWalker method to create a TreeWalker object. This is a practice that is used in a number of Chrome extensions!
// create a TreeWalker of all text nodes var allTextNodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT), // some temp references for performance tmptxt, tmpnode, // compile the RE and cache the replace string, for performance cakeRE = /cake/g, replaceValue = "pie"; // iterate through all text nodes while (allTextNodes.nextNode()) { tmpnode = allTextNodes.currentNode; tmptxt = tmpnode.nodeValue; tmpnode.nodeValue = tmptxt.replace(cakeRE, replaceValue); }
To replace parts of text with another element or to add an element in the middle of text, use DOM splitText
, createElement
, and insertBefore
methods, example.
See also how to replace multiple strings with multiple other strings.
Don’t use innerHTML or innerText or jQuery .html()
// the innerHTML property of any DOM node is a string document.body.innerHTML = document.body.innerHTML.replace(/cake/g,'pie')
- It’s generally slower (especially on mobile devices).
- It effectively removes and replaces the entire DOM, which is not awesome and could have some side effects: it destroys all event listeners attached in JavaScript code (via addEventListener or .onxxxx properties) thus breaking the functionality partially/completely.
- This is, however, a common, quick, and very dirty way to do it.