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).
Can the JavaScript command .replace replace text in any webpage? I want to create
Share
The
.replacemethod 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!
To replace parts of text with another element or to add an element in the middle of text, use DOM
splitText,createElement, andinsertBeforemethods, example.See also how to replace multiple strings with multiple other strings.
Don’t use innerHTML or innerText or jQuery
.html()