jQuery Find and Replace String without HTML ID

May 23, 2012

I’m going to begin posting more day to day pieces of projects I’m working on, in particular solutions to problems I come across along the way.

I’ve been updating an e-commerce checkout page for a client, but since the store uses a hosted solution I often come across parts of pages I have no control over the HTML or content strings. For example, this specific hosted solution allows gift wrapping with a gift message input field, but my client only wishes to provide a gift message, no wrapping. Unfortunately the h4 element always says ‘Gift Wrap’ regardless if wrapping is turned off and messaging turned on. Therefore I used a combination of the jQuery contains selector with the jQuery replaceWith function to replace ‘Gift Wrap’ with ‘Gift Message’. Like so:

$(document).ready(function() { $("h4:contains('Wrap')").replaceWith("<h4>Gift Message</h4>"); });

I could have also used JavaScript find and replace by element ID, but the string I was looking to replace did not have a unique element ID that I could access. The jQuery solution above works around not using an HTML ID and instead focuses on the specific text.