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
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
This solution might help you.
JavaScript not executed if:
<script type=”text/xml”>
doesn’t execute<script type=”text/xml” type=”text/javascript”>
doesn’t execute as well because only the first type is consideredso 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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With