Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline script rendered as text content

I have DOM objects given as an HTML string and are inserted into an HTML page by AJAX with the jQuery method replaceWith(). The HTML string includes a <div> element and an inline <script> that works on it, and the jQuery command is like the following:

$('#foo').replaceWith('<div>Some Content</div><script>someJavaScriptFunction();</script>');

After this AJAX is executed, the <div> element is rendered correctly, and the script inside the <script> is working, but in addition to that, the content of the inline <script> is rendered verbatim on the page. Why is this happening? How can I avoid this? When I see the corresponding part on Chrome developers tools, the inline script appears only once (which is what I intended).

like image 342
sawa Avatar asked Feb 18 '26 19:02

sawa


1 Answers

You need to escape the / forward slash of closing script tag.

Live Demo

$('#foo').replaceWith('<div>Some Content</div><script>someJavaScriptFunction()<\/script>');
like image 143
Adil Avatar answered Feb 20 '26 07:02

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!