'wat'.replace('a', 'ha'); //=> 'what'). Sometimes, though, you want to do a search and replace on text in a whole html document that includes html tags and things that aren’t just text. I had to do that recently and found it wasn’t as obvious as I first thought.
Let’s say I wanted to replace all occurrences of
rats. Simple enough.
My first thought was to do something like this:
This has a few problems. First, it changes all occurrences of
rats, even those inside html tag properties to
<a href="mysite.com/hats">hats</a> becomes
<a href="mysite.com/rats">rats</a>. Ideally, I would want
I wasn’t sure what to do so I did a little searching and came across Phrogz’s stackoverflow answer to a related question that explained
document.createTreeWalker as a solution. This gives us access to each text node in the document like so:
What this does is finds all text nodes inside the
html tag on the document and replaces its value with the newly hats/rats-swapped text. This won’t affect binding on any element on the page (even if you crazily have an event bound to a text node) and leaves tag attributes (like the aforementioned
Hopefully this article saves you some time if you ever need to do some html find and replacing!