On the W3 tutorial, it shows htis code:
First of all, W3Schools has nothing to do with W3. Their tutorials were pretty horrible before people started complaining and their confusing name implies that they are somehow connected to W3, but in reality they aren't.
Second of all, this method is not needed anymore. There are no used browsers that don't support JS cleanly (links
, lynx
, etc. have no troubles with JS code whatsoever).
That being said, the code is supposed to do this:
<!--
I am a HTML comment
-->
<!--
If I am placed in a JS block, the web browser should ignore me
alert('and me');
-->
<!--
If you comment out the HTML comment ending tag, apparently
the browser will treat the comment as JS code *only*
if the browser supports JS.
//-->
If you make it like this, you'll get syntax error:
<script type="text/javascript">
<!--
document.getElementById("demo").innerHTML=Date();
-->
</script>
JavaScript doesn't know HTML's comment closing -->
, so it has to be commented out of script.
There is no need to use HTML-comments to separate JavaScript, except if you're using a simple text editor which colours the code (NoteTab etc.).
In browsers that do understand JavaScript the opening <--
html comment is ignored and the JS code is executed. The JS comment //
on the last line then prevents the closing -->
being taken as an error by the JS engine. In browsers that don't understand JavaScript everything between <--
and -->
is taken as an html comment and ignored.
This whole thing was a precaution for older browsers that didn't know about JS. It is not necessary for any modern browser.
If you want to comment out a block of JS enclose the block in /*
and */
.
It does all get commented out.
In a bowser without Javascript everything between <!--
and -->
will be commented out.
Try to think of it this way: If you tried this code
<script type="text/javascript">
-->
</script>
then Javascript would throw an error.