adequately good

decent programming advice

written by ben cherry




Search/Replace in the DOM with jQuery

Ever had a need to to a text search/replace through the DOM? For articles in drafting on this blog I often use the form (TODO: something) as notes for myself to do some more research. I don't want them sticking around in the text I publish, so I highlighted them red (only for myself). Here's the script I used to accomplish that:

jQuery(function () {
	jQuery(":contains(TODO)").not(":has(:contains(TODO))").each(function () {
		var that = $(this),
			html = that.html();

		html = html.replace(/(\(TODO:.*?\))/g, "<span class=\"todo\">$1</span>");
		that.html(html);
	});
});

The trick is to find only the nodes that contain the actual text, not ancestors of such nodes, which is what you would get with just jQuery(":contains(TOOD)"). Filtering with .not(":has(:contains(TODO))") ensures you've got the bottom most ones. I tried doing this with the ":not()" filter, but it didn't work. I guess that might be a jQuery bug, but the .not() method is a fine alternative.

filed under javascript and jquery