<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?
. 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.
The document. write() method writes a string of text to a document stream opened by document.
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.
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>
It is because the <!--
in your javascript is parsed as the start of a comment before the JavaScript runs.
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-->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With