javascript - how to insert a script tag to div?

后端 未结 4 1506
猫巷女王i
猫巷女王i 2020-12-21 08:34

How to do that:

document.getElementById(\'target\').innertHTML = \"<script> alert(1); <script>\";
相关标签:
4条回答
  • 2020-12-21 09:08
    document.getElementById('target').innertHTML = '<script type="text/javascript"> alert(1); </script>';
    
    0 讨论(0)
  • 2020-12-21 09:21

    I believe it is better to use pure DOM manipulation. Like this :

    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.value = 'alert(1)';
    document.getElementById('target').appendChild(s);
    
    0 讨论(0)
  • 2020-12-21 09:27

    Just don't escape your < and >s:

    document.getElementById('target').innertHTML = "<script> alert(1); <\/script>";
    
    0 讨论(0)
  • 2020-12-21 09:28

    You cannot use innerHTML for scripts anymore. It won't work and the console will not show any error. Instead you dynamically add scripts.

    This is for external scripts:

    var newScript = document.createElement("script");
    newScript.src = "http://www.example.com/my-script.js";
    target.appendChild(newScript);
    

    And this is for inline scripts:

    var newScript = document.createElement("script");
    var inlineScript = document.createTextNode("alert('Hello World!');");
    newScript.appendChild(inlineScript); 
    target.appendChild(newScript);
    

    Credit to Daniel Crabtree

    0 讨论(0)
提交回复
热议问题