Quantcast
Viewing latest article 2
Browse Latest Browse All 3

DOM text search/replace with jQuery

I recently did a quick hack to modify a bunch of text (phrases) on an already rendered HTML page. It was inconvenient to manually select single elements and modify the text – what I needed was a global search/replace.

Turns out it’s quite easy to build one, so I did. I created a jQuery plugin that can go through all text nodes inside an element, match them against a fixed string or a regular expression, and replace it. The replacement can be a fixed string, a regular expression replacement, or a result of a function. Functions can also be (ab)used to modify the element beyond just changing the text.

You can get the plugin from GitHub, and see it in action on JSFiddle. In case anyone cares, I’m releasing it to Public Domain. It should work across all browsers, although it can be quite slow on big, heavy pages with a lot of text.

Beyond quick hacks, this plugin is quite useful for things like page translation, simple A/B tests and other uses where you need to manipulate text based on its content, not the page structure.


Viewing latest article 2
Browse Latest Browse All 3

Trending Articles