We help IT Professionals succeed at work.

JavaScript: Add in head using document.write

hankknight
hankknight asked
on
What is wrong with my code?  I want to be able to add JavaScript using document.write.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>

<script type="text/javascript">

// <![CDATA[
<script type="text/javascript">

 document.write(' \
 <'+'script type="text/javascript"> alert(123); <'+'/script>\

 ');
// ]]>

</script>
</head> 
<body> 

<h1>Hello</h1>

</body>
</html>

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
get rid of line 10 (you already opened the script tag on line 7) and on line 14 add a \ at the end because you string continues on line 15.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>

<script type="text/javascript">// <![CDATA[


 document.write(' \
 <'+'script type="text/javascript"> alert(123); <'+'/script>\
\
 ');
// ]]>

</script>
</head> 
<body> 

<h1>Hello</h1>

</body>
</html>

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.