The function below works fine for me:
// Note this *is* JQuery, see below for JS solution instead function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); $(selector).each(function () { var $this = $(this); if (!$this.children().length) $this.text($this.text().replace(matcher, newText)); }); }
Here is a usage example:
function replaceAllText() { replaceText('*', 'hello', 'hi', 'g'); } $(document).ready(replaceAllText); $('html').ajaxStop(replaceAllText);
You can also use direct replacement like this:
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
But be careful, as this can affect tags, css and scripts.
EDIT: Regarding a clean JavaScript solution, use this method:
function replaceText(selector, text, newText, flags) { var matcher = new RegExp(text, flags); var elems = document.querySelectorAll(selector), i; for (i = 0; i < elems.length; i++) if (!elems[i].childNodes.length) elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText); }
Ziad Sep 06 '14 at 10:03 2014-09-06 10:03
source share