How to insert JavaScript with JavaScript?

0

I'm trying to insert JavaScript into an HTML page with JavaScript, after the page has already loaded, but I can not make the new code work, what's the problem?

var javascript = "<script> function alerta() { alert('ok'); }</script>";

var button = "<button type='button' onclick='alerta();'>start</button>";

var body = document.getElementsByTagName('body')[0];

body.insertAdjacentHTML('beforeend', javascript);

body.insertAdjacentHTML('beforeend', button);

Note: I can not put the code inside onclick !

    
asked by anonymous 08.07.2017 / 22:13

3 answers

1

An alternative would create the script as in the example below, and instead of insertAdjacentHTML() I used the appendChild() method

var script = document.createElement("script");
script.type = 'text/javascript';
script.innerHTML = "function alerta(){alert('ok');}";

var button = "<button type='button' onclick='alerta();'>start</button>";

var body = document.getElementsByTagName('body')[0];

body.appendChild(script);

body.insertAdjacentHTML('beforeend', button);
    
08.07.2017 / 22:40
0

The <javascript> tag is not a search, it would be <script> . But when you insert </script> with JavaScript inside HTML this does not work. It does not work because some browsers come with the </script> closing tag and they think it's the HTML tag of the script you're running and that gives you an error.

Make the function with "normal" JavaScript, and push the button as you were doing.

function alerta() { alert('ok'); }
var button = "<button type='button' onclick='alerta();'>start</button>";

var body = document.body;
body.insertAdjacentHTML('beforeend', button);
    
08.07.2017 / 22:41
-2

Try using this to load the code

<script>
function myFunc(){
    // Aqui vai o codigo que vai rodar antes da pagina ser carregada...
}
window.onload = myFunc;
</script>
    
08.07.2017 / 22:43