3
document.body.innerHTML = "<script>alert(11);</script>"

$("body").html("<script>alert(11);</script>")

innerHTML is not executed.

jQuery html() is executed.

Why so?

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • possible duplicate of [Can scripts be inserted with innerHTML?](http://stackoverflow.com/questions/1197575/can-scripts-be-inserted-with-innerhtml) – hjpotter92 Aug 06 '14 at 01:30

3 Answers3

2

Without getting into the theoretical questions of why jQuery chose to do this, the jQuery html() behaves differently than the native innerHTML. By default, jQuery will find the script tags within the HTML, and load then asynchronously. If this behavior is undesirable, you can use $.parseHTML to prevent this from happening by setting the third argument to false.

$("body").empty().append($.parseHTML("<script>alert(11);</script>", document, false));

Note that the script tags will not be added to the DOM using this method.

Conversely, if you wish to achieve the same affect as your jQuery statement in vanilla JS, you can do the following.

var script = document.createElement('script');
script.text = 'alert(11);';
document.body.innerHTML = '';
document.body.appendChild(script);
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
0

Try this...

var x = document.createElement('script');
var y = document.getElementsByTagName('script')[0];
x.text = "alert(11);"
y.parentNode.insertBefore(x, y);
jned29
  • 477
  • 12
  • 50
0

Using innerHTML will stop the script from executing according to the documentation in simple words without going into details.

<script type="text/javascript">
    var script = document.createElement('script');
    script.appendChild(document.createTextNode("alert('11')"));
    document.body.appendChild(script);
</script>
ahjashish
  • 573
  • 1
  • 3
  • 13