5
<p>hello</p>
<script type="text/javascript">
document.write("<!--");
</script>
<p>world</p>
<script type="text/javascript">
document.write("-->");
</script>
<p>nihao</p>

I thought the output of this piece of HTML is

hello
nihao

But it turns out as below:

hello
");
nihao

How should I achieve what I expected? What's the problem here?

JackWM
  • 10,085
  • 22
  • 65
  • 92

5 Answers5

8

Well, the first JavaScript element is executed which leads to a representation like this:

<p>hello</p>
<!--
<p>world</p>
<script type="text/javascript">
document.write("-->");
</script>
<p>nihao</p>

So the HTML comment start you just added spans into your next JavaScript element and the resulting output is just as you described. To answer your second question, whats wrong with the following?

<p>hello</p>
<script type="text/javascript">
document.write("<!--<p>world</p>-->");
</script>
<p>nihao</p>
str
  • 42,689
  • 17
  • 109
  • 127
5

It is because the <!-- in your javascript is parsed as the start of a comment before the JavaScript runs.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
5

There have been some useful answers, but if you actually want to create a comment and insert it into your document then you need to use the createComment() function:

var comment = document.createComment("This is a comment") 
​document.appendChild(comment);​

Will output:

<!--This is a comment-->
Jivings
  • 22,834
  • 6
  • 60
  • 101
2

To get exactly result you expect:

<p>hello</p>
<script id="ahh" type="text/javascript">
document.write("<!"+"--"+"<p>world<p>--"+">");
document.getElementById('ahh').remove()
</script>
<p>nihao</p>​

anyway it is pretty bad idea.

zb'
  • 8,071
  • 4
  • 41
  • 68
0

If, like me, you came across this question wanting to hide an element when JavaScript is enabled, consider using the <noscript> tag instead!

ianh
  • 836
  • 1
  • 5
  • 15