How to insert Javascript with Javascript?

Asked

Viewed 118 times

0

I’m trying to insert Javascript into an HTML page with Javascript, after the page has already loaded, but I can’t 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 cannot put the code inside the onclick!

  • What would that tag be <javascript>?

3 answers

1


One alternative would create the script according to the example below, and instead of insertAdjacentHTML() I used the method appendChild()

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);

  • What’s the difference?

  • @Denilsonoliveira the method appendChild adds an element in the DOM, already the insertAdjacentHTML, parses a string as html and inserts at the specified position.

0

The tag <javascript> is not search, would be <script>. But when you insert </script> with Javascript inside HTML this doesn’t work. It doesn’t work because some browsers see the tag closing </script> and they think it’s the script’s HTML tag that you’re running and that’s a mistake.

Do the function with "normal" Javascript, and insert 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);

-2

Try Use This to Load the Code

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.