Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 477
JackWM Avatar asked Dec 09 '12 21:12

JackWM


People also ask

Why is Document write () not recommended anymore?

. write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process.

What does Document write () function do?

The document. write() method writes a string of text to a document stream opened by document.

Why is there a dot in the document write () command?

write(), you are basically saying “Perform the method write(), which acts on/belongs to the variable document.” The dot just means that whatever is on the right side of the dot is a method or property of whatever is on the left side.


3 Answers

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>
like image 116
str Avatar answered Oct 19 '22 05:10

str


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

like image 22
Ted Hopp Avatar answered Oct 19 '22 07:10

Ted Hopp


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-->
like image 5
Jivings Avatar answered Oct 19 '22 06:10

Jivings