1

(Please do not mark this question as a duplicate to Can scripts be inserted with innerHTML? because it is not.)

I wonder why a script element created via innerHTML does not get executed when appended to DOM:

container=document.createElement('div');
container.innerHTML='<script>alert()</'+'script>';
document.body.appendChild(container.firstChild);

... while the same script created via document.createElement gets executed when appended to DOM:

script=document.createElement('script');
script.innerHTML='alert()';
document.body.appendChild(script);

It looks to me as inconsistency: in both cases I append a script element (which looks the same), so I do not understand why appending the same script gives different results depending on how this script was generated.

  • I know you requested this not be marked as a duplicate, but it _is_. A quick Google search shows this question has been asked and answered several times already. – rossipedia Jun 18 '17 at 16:27

1 Answers1

0

When you create a 'script' tag, the browser evaluate the script expression but when you create a 'div' tag, even if a script is inside the browser won't evaluate that script.

By default, when you append an element after the DOM loads, the browser won't check/run if you add a script inside UNLESS it is a script pure element.

Bitito
  • 191
  • 6
  • Script inside a div also works, as long as it is created via createElement: container=document.createElement('div'); script=document.createElement('script'); script.innerHTML='alert()'; container.appendChild(script); document.body.appendChild(container); – Grigory Hatsevich Jun 18 '17 at 16:55