First of all, don't confuse HTML, CSS and JavaScript comments. They are not interchangeable.
Let's start with your first HTML snippet:
<span style='color: red; <!-- background-color: green; -->'>Test</span>
There is no comment here. You cannot put HTML comments in attributes. For example, if you change that attribute from being style
to being title
, you'll notice that the entire attribute - "comment" and all - ends up in the hover/tooltip text: http://jsfiddle.net/Mw3wy/
That means the <!-- background-color: green; -->
content is being included in the document content - ie it's not commented out.
Next.
<span style='color: red; /* background-color: green; */'>Test</span>
Here we have nested formatting: we have an HTML element, with an attribute whose value is multiple CSS declarations. In CSS, you can create comments using /* C-style */
block comments.
So here we have no HTML comments, but we do have CSS comments. That means the content isn't commented out from being part of the HTML document content, but it is commented out from the CSS declarations - so whatever engine is responsible for parsing the CSS and rendering elements on the page based on those declarations will ignore it.
But if we use that same syntax in a different context:
<span title='color: red; /* background-color: green; */'>Test</span>
... now there is no comment, since there is no need for CSS syntax in this snippet.
Let's talk about the next two at the same time:
<span onclick="alert('1'); // alert('2');">Click me!</span>
<span onclick="alert('1'); /* alert('2'); */">Click me!</span>
These both have no HTML comments, but they do contain JavaScript comments. Again, we have nested formats: we have an HTML element with one attribute which is interpreted (and formatted) as JavaScript code, so you can use JavaScript-style commenting within that context.
This, however...
<span onclick="alert('1'); <!-- alert('2'); -->">Click me!</span>
... is a syntax error for your JavaScript. You might get that alert('1')
to work, but any further code which comes after it won't execute: http://jsfiddle.net/Ma9Tb/
That's because you're using HTML comments in a context where they can't be used. You can't use HTML comments within a <script>
element either: http://jsfiddle.net/SbZ2m/
So the important thing is to keep track of when you have nested formatting. For example, you could have an HTML attribute which contains JavaScript code - including a comment - which then manipulates a string of CSS formatted data - which includes a CSS comment: http://jsfiddle.net/EGK5X/
<button onclick="this.setAttribute('style', 'color:red;/*CSS comment!*/background:black;'); // JavaScript comment!">Click on me!</button>
If you confuse this, you'll end up with problems like this one.