Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace html part by javascript

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

like image 632
indapublic Avatar asked Jan 04 '14 08:01

indapublic


2 Answers

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

like image 157
Aneesh Dogra Avatar answered Sep 17 '22 01:09

Aneesh Dogra


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));
like image 29
Zaheer Ahmed Avatar answered Sep 19 '22 01:09

Zaheer Ahmed