How do I add a JavaScript line (not an exteral.js file)?
I want to add a script tag that executes one line of JavaScript in the head of the document, instead of adding a script tag that is empty and uses the src attribute.
Here's what I have so far:
<script type="text/javascript">
var scriptContents = 'alert("hi")';
var theScript = document.createElement('script');
theScript.type = 'text/javascript';
theScript.appendChild(scriptContents);
document.getElementsByTagName('head')[0].appendChild(theScript);
</script>
This is the part of appendChild (scriptContents) that I am having trouble with. How do I change this to get a warning in the browser?
+2
source to share
2 answers
You cannot do
theScript.appendChild(scriptContents);
as appendChild()
only adds nodes, it cannot add text. You need to make the text node with:
var scriptContents=document.createTextNode('alert("hi");')
However, as Jake mentioned above, you probably just want to do:
eval('alert("hi")');
+4
source to share