You can use jQuery itself to help you with the replacement:
$(html) .contents() .filter(function() { return this.nodeType == 1 || this.nodeType == 3; }).each(function() { this.textContent = this.textContent.replace(replacepattern, 'whatever'); });
Note that the last occurrence of Hello not replaced, since it is technically not valid to have the text node as a child of the <body> .
In addition, you will have to change it to work in IE <9 or 10; in principle, the browser will support node.textContent :)
Update
The problem was somewhat more complex; or maybe my mind makes it more difficult than it is. Replacing text nodes with jQuery is not an easy task, so this requires some clean JS:
$('<div><p>Hello world!</p><p><img src="hello.jpg" alt="Hello"/></p>Hello</div>') .find('*') .andSelf() .each(function() { for (var i = 0, nodes = this.childNodes, n = nodes.length; i < n; ++i) { if (nodes[i].nodeType == 3) { var txt = nodes[i].textContent || nodes[i].innerText, newtxt = txt.replace(/Hello/g, 'Bye'); if (txt != newtxt) { var txtnode = document.createTextNode(newtxt); this.replaceChild(txtnode, nodes[i]); } } } }) .end() .end() .appendTo('body');
source share