I want to add DOM element to head section of HTML. jQuery does not allow adding DOM element script to the head section and they execute instead, Reference.
I want t
var script = $('<script type="text/javascript">// function </script>')
document.getElementsByTagName("head")[0].appendChild(script[0])
But in that case script will not be executed and functions will be not accessible in global namespase.
To use code in <script>
you need do as in you question
$('head').append(script);
you could do:
var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "script_source_here";
(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(scriptTag);
<script type="text/JavaScript">
var script = document.createElement('SCRIPT');
script.src = 'YOURJAVASCRIPTURL';
document.getElementsByTagName('HEAD')[0].appendChild(script);
</script>
try this
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';
document.getElementsByTagName('head')[0].appendChild(script);
As per the author, they want to create a script in the head, not a link to a script file. Also, to avoid complications from jQuery (which provides little useful functionality in this case), vanilla javascript is likely the better option.
That may possibly be done as such:
var script = document.createTextNode("<script>alert('Hi!');</script>");
document.getElementsByTagName('head')[0].appendChild(script);
try out ::
var script = document.createElement("script");
script.type="text/javascript";
script.innerHTML="alert('Hi!');";
document.getElementsByTagName('head')[0].appendChild(script);