tags:

views:

56

answers:

2

I have a JavaScript function, in this function i will write

<script type='text/JavaScript' language='JavaScript'>alert('ha')</script>

But while executing this page it doesn't work. This is my code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;

<head>
<script language="javascript" type="text/javascript">
function asd()
{
 document.write("<script language='javascript' type='text/javascript'>alert('asdasd');</" + "script>");
}
</script>
</head>
<body onload="asd();">
 <span id="gdfg"></span>
 <span>dgdfghfghfghfg</span>
</body>
</html>
+2  A: 

Don't use document.write after the page has loaded, cause it will reset the whole document. If you want to add some new elements (like <script> tags) to the document, use DOM (document.createElement, element.appendChild, etc.).

Rafael
+2  A: 

What Rafael meant was this

window.onload=function() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = '/myalert.js';
  document.getElementsByTagName("head")[0].appendChild(script);
}

or

window.onload=function() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  var textNode = document.createTextNode('alert("bla");')
  script.appendChild(textNode)';
  document.getElementsByTagName("head")[0].appendChild(script);
}
mplungjan
I really can't imagine a case where the second example could be useful. Can you?
Marcel Korpel
This example code is indeed not very useful, but it's just a question and the author may be working with more complex code.
Rafael
Yes, I only gave the second example to allow the construct of the original question without judging what the need could be. For example extracting script from an ajax reply
mplungjan