5

I have problem: I need to replace some word on page with needed html. For example:

t = $('body').html();
t = t.replace(/Myword/g, '<div></div>');
$('body').html(t);

It is working successfully. But... If body contains javascript tag - JS running again.

If I use document.body - it working

t = document.body.innerHTML;
t = t.replace(/Myword/g, '<div></div>');
document.body.innerHTML = t;

But I am interested in jQuery solution. Maybe you have it?

Thanks in advance

Anshu Dwibhashi
  • 4,617
  • 3
  • 28
  • 59
indapublic
  • 2,208
  • 9
  • 38
  • 49

4 Answers4

3

A simple solution would be to ignore all the script tags.

t = $('body').clone().find("script").remove().end().html();
t = t.replace(/Myword/g, '<div></div>');
$('body').html(t);

Demo

Aneesh Dogra
  • 740
  • 5
  • 30
1

This solution might help you.

JavaScript not executed if:

  1. JavaScript inside the <script type=”text/xml”> doesn’t execute
  2. JavaScript inside the <script type=”text/xml” type=”text/javascript”> doesn’t execute as well because only the first type is considered

so change type:

function preventJS(html) {
     return html.replace(/<script(?=(\s|>))/i, '<script type="text/xml" ');
}

and use it:

t = $('body').html();
t = t.replace(/Myword/g, '<div></div>');
$('body').html(preventJS(t));
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
1

As Arun mentioned in the comments, you should target the elements more specifically. It sounds like <script> tags will be re-evaluated if you use JQuery to get the entire <body> content and then re-insert it. Try wrapping the desired content in a <div>:

<body>
    <div id="wrapper">
        <p>Text that will be altered</p>
    </div>
    <script type="text/javascript">
        //javascript code
    </script>
</body>

Then your code that will replace text can be:

t = $('#wrapper').html();
t = t.replace(/Myword/g, '<div></div>');
$('#wrapper').html(t);
AnalogWeapon
  • 550
  • 1
  • 4
  • 16
  • You might want to rephrase that to make it clear that capturing the entire content of `` is a requirement. – AnalogWeapon Jan 08 '14 at 14:43
  • [This SO question](http://stackoverflow.com/q/5550633/1530115) is asking the same thing, and they are discussing some other options there. Good luck! – AnalogWeapon Jan 08 '14 at 14:47
1

A better way would be to just replace "Myword" in the most specific element possible. This will only replace Myword in the textNodes which contain it and nowhere else.

var each = Array.prototype.forEach;

var $myword = $(":contains('Myword')");
$myword.each(function() {
    each.call(this.childNodes, function(ele) {
        if(ele.nodeType === 3 && ele.nodeValue.indexOf('Myword') >= 0) {//if ele is a text node and contains myword
            ele.nodeValue = ele.nodeValue.replace(/Myword/g, "some text");
        } 
    }, this);
});

Try running it on this page

megawac
  • 10,953
  • 5
  • 40
  • 61