The right way to write comments in HTML is: <!-- Comment -->
. For Javascript, the right way to write comments is // Comment
or /* Comment */
, while for CSS, comments are written as /* Comment */
.
What is the right way to write comments in style
and onclick
attributes of HTML elements?
For example, which is right? This:
<span style='color: red; <!-- background-color: green; -->'>Test</span>
Or this:
<span style='color: red; /* background-color: green; */'>Test</span>
Tested in a fiddle, both codes produced the same result of the word "Test" with a red color and no background color.
Also, which is correct? This:
<span onclick="alert('1'); // alert('2');">Click me!</span>
this:
<span onclick="alert('1'); /* alert('2'); */">Click me!</span>
Or this:
<span onclick="alert('1'); <!-- alert('2'); -->">Click me!</span>
Because, according to this fiddle, all 3 elements produce an alert saying "1" when clicked.
I would appreciate your answer.
In HTML, a comment is text enclosed within < ! ╌ ╌> tags. This syntax tells the browser that they are comments and should not be rendered on the front end.
Single line comments start with // . Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
The most common use of the COMMENT attribute is to give information or instructions to the user. The COMMENT attribute can be used for different sort of form elements: Form field definitions, to show a message when the field gets the focus. Action views, to give a hint to the user about the action.
The syntax of the style
attribute is essentially the same as CSS files. So the comment syntax is the same as in CSS, which is /* ... */
The syntax of onEVENT
attributes is Javascript. Javascript has two types of comments: //
that comments until the end of the line, and /* ... */
that encloses comments. If the onEVENT
attribute is a single line, if you use //
it will comment the rest of the attribute. If you want to end the comment earlier, use /* ... */
. You can also have newlines in an onEVENT
attribute; then the //
comment will only last to the newline.
Example:
<div id="foo" onclick="alert('foo'); // comment */; alert('bar');">
// comment
</div>
<div id="bar" onclick="alert('foo'); /* comment */ alert('bar');">
/* */ comment
</div>
<div id="foobar" onclick="alert('foo'); // comment
alert('bar')">
// comment multi-line
</div>
In // comment
, the second alert()
is commented out. In /* */ comment
, both alerts execute. Also, both alerts execute in // comment multi-line
.
Amazingly, the SO code highlighter gets this right!
FIDDLE
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