alert(11);" $("body").html("

Script Execution - innerHTML, jQuery html ()

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

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

      

innerHTML

not executed.

Performed

jQuery html()

.

Why is that?

+3


source to share


3 answers


Without getting into theoretical questions about why jQuery chose to do this, jQuery html()

behaves differently than native innerHTML

. By default jQuery will find script tags in HTML and load 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));

      

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



Conversely, if you want to achieve the same effect 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);

      

+2


source


Try it...



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

      

0


source


Using innerHTML will stop the script execution according to the documentation in simple terms, without going into details.

<script type="text/javascript">
    var script = document.createElement('script');
    script.appendChild(document.createTextNode("alert('11')"));
    document.body.appendChild(script);
</script>

      

0


source







All Articles