3

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).

1
  • 1
    can you try changing '</script>' to '</scr'+'ipt>'? Commented May 27, 2013 at 9:11

1 Answer 1

3

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

Live Demo

$('#foo').replaceWith('<div>Some Content</div><script>someJavaScriptFunction()<\/script>');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.