document.body.innerHTML = "<script>alert(11);</script>"
$("body").html("<script>alert(11);</script>")
innerHTML
is not executed.
jQuery html()
is executed.
Why so?
document.body.innerHTML = "<script>alert(11);</script>"
$("body").html("<script>alert(11);</script>")
innerHTML
is not executed.
jQuery html()
is executed.
Why so?
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);
Try this...
var x = document.createElement('script');
var y = document.getElementsByTagName('script')[0];
x.text = "alert(11);"
y.parentNode.insertBefore(x, y);
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>