") not working as expected?

hello

world

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
source share
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
source

This is because <!-- in your javascript is parsed as the beginning of a comment before JavaScript starts.

+5
source

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
source

To get the exact 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> 

In any case, this is a pretty bad idea.

+2
source

All Articles