0

Is it possible to write function using innerHTML in javascript, like below :

eg:

frameDoc.body.innerHTML ='<script type="text/javascript">';
frameDoc.body.innerHTML+='function highlightSearch(){';
frameDoc.body.innerHTML+='alert("example");';
frameDoc.body.innerHTML+='return true;}';
frameDoc.body.innerHTML+='</script>';
2
  • 2
    What is the problem you want to solve by doing this- there aren't many situations this would be the best way of doing things. Commented Jul 3, 2015 at 9:58
  • Or more neatly via document.createElement('script') Commented Jul 3, 2015 at 10:00

2 Answers 2

3

Yes, it is possible to add a function to an HTML file trought innerHTML. In fact, most of the third parties API do so. They append their own script using this system or document.createElement('script').

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to execute the code you should change approach. The best way to do so is to create a dynamic script node and add it to the document. A worse approach but that still works is using document.write.

document.write('<script type="text/javascript">');
document.write('function highlightSearch(){');
document.write('alert("example");');
document.write('return true;}');
document.write('highlightSearch()');
document.write('<\/script>');

Note that I added document.write('highlightSearch()'); to execute the function.

2 Comments

Please suggest me by using innerHTML.
Instead of innerHTML, you can use appendChild. var g = document.createElement('script'); var s = document.getElementsByTagName('script')[0]; g.text = "alert(\"hi\");" s.parentNode.insertBefore(g, s);

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.