Search code examples
javascripthtmldocument.write

Why document.write("-->") does not work as expected?


<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?


Solution

  • 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>