Why is document.write ("->") not working 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 HTML snippet
hello nihao But it turns out, as shown below:
hello "); nihao How do I achieve what I expected? What is the problem?
+4
4 answers
Well, the first JavaScript element is executed, which leads to a view like this:
<p>hello</p> <!-- <p>world</p> <script type="text/javascript"> document.write("-->"); </script> <p>nihao</p> So, the HTML comment will start adding only your spaces to your next JavaScript element, and the result will be the same as you described. To answer your second question, what happened to the following?
<p>hello</p> <script type="text/javascript"> document.write("<!--<p>world</p>-->"); </script> <p>nihao</p> +7
There were some helpful answers, but if you really want to create a comment and paste it into your document, you need to use the createComment() function:
var comment = document.createComment("This is a comment") document.appendChild(comment); It will display:
<!--This is a comment--> +4