5

It's so hard to search for symbols in Google, so I ask here instead.

<!-- looks like a comment for me, but it doesn't work like html. Or it's a one line comment just like // ?

What is the purpose and benefit of using this? Thanks

sample code :

<script type="text/javascript"> <!-- alert("example"); //--> </script> 
1
  • Do you have an example of where you saw it? Commented May 9, 2011 at 4:44

4 Answers 4

7

It's an old method of hiding JavaScript from browsers that would treat the text node of a script element as normal text (and display your code).

Douglas Crockford recommends you don't use it anymore.

Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. <!-- //--> is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.

Sign up to request clarification or add additional context in comments.

1 Comment

now it all make sense.. It's an existing codes and it's everywhere. So will just leave them there.
0

It is HTML -- it's an HTML comment. Often used in a JavaScript block for CDATA: http://en.wikipedia.org/wiki/CDATA

Comments

0

JavaScript treats <!-- as a single line comment, the same as //. This is so you can wrap your JS code such that it looks like an HTML comment to browsers that don't understand JS:

<script> <!-- alert('test'); // --> </script> 

6 Comments

No it doesn't. In fact your answer doesn't make sense. Javascript executes the code inside. HTML treats it as a comment.
@EJP: HTML only treats it as a comment if your browser doesn't understand Javascript or the <script> tag at all. This hasn't been the case in any semi-popular browser for over a decade now. Which means that the statement in the answer is correct, though I'm not sure it's treated as a single-line comment. I believe that the symbol is simply ignored by most Javascript engines if it is at the start of a <script> block.
@Matthew it's treated as single line comment in chrome. I tried it out in jsfiddle
@Matthew Scharley: that doesn't change the fact that Javascript doesn't treat it as a comment at all. Otherwise the entire construct would be pointless.
@EJP, it's treated as a single line comment.
|
0

Comments in html

  • <!-- ... -->

Comments in javascript are like c:

  • One line comment = // ...
  • Multi line comment = /* ... */

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.