sawa
sawa

Reputation: 168179

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

Upvotes: 3

Views: 625

Answers (1)

Adil
Adil

Reputation: 148150

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

Live Demo

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

Upvotes: 3

Related Questions