2

I have an HTML document

...

<div id="test"></div>

...

Then i dynamicaly load some context to #test div.

function change()
{
ws = document.getElementById(id);
str = '<script>function ttest(){window.alert("Yahoo!!!")}</script><select><option onclick="ttest();">1</option><option >2</option></select>';
ws.innerHTML = str;
}

window.onload = change();

When the page is loaded a custom script

<script>function ttest(){window.alert("Yahoo!!!")}</script>

doesnt work.

It works perfect when its put static without any innerHTML. Also it works when its not a custom function.

How can i make my custom function work, when it was loaded dynamically using innerHTML or/and AJAX+innerHTML ?

6
  • What do you mean by "doesn't work" ? What are you trying to do ? Commented Jan 18, 2017 at 14:59
  • I received a messafe that the function change doesnt exist. Commented Jan 18, 2017 at 15:01
  • But why would you inlude a javascript code like that ? Commented Jan 18, 2017 at 15:02
  • actually my code is a little bit more complex ))). This one is just to make a question and find a solution on how to run custom javascript which is loaded dynamically. I am not afraid of sharing but there are too much text .... Commented Jan 18, 2017 at 15:05
  • try to write str = '<scr' + 'ipt>function ttest(){window.alert("Yahoo!!!")}</scr' + 'ipt>'; Commented Jan 18, 2017 at 15:35

1 Answer 1

1

Add your script to the document.head via createElement. So something like this:

var script = document.createElement("script");
script.innerHTML = "function ttest() { alert('Yahoo'); }";
document.head.appendChild(script)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works....!!!! But with one correction - document.getElementsByTagName('head') instead of document.head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.