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).
You need to escape the / forward slash of closing script tag.
Live Demo
$('#foo').replaceWith('<div>Some Content</div><script>someJavaScriptFunction()<\/script>');
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