Cary Bondoc Cary Bondoc - 10 months ago 57
HTML Question

Reason why I can't insert a comment inside the HTML tag?

Are there any reason why I can't insert a comment inside the HTML tag?

Sample: In HTML (Not Possible)

<img <!-- sample comment--> src="" alt="Sample Picture" class="img-circle center-block" />

While in JavaScript it can be easily done.

Sample: In JS (Possible)

verticalCentered: /* Sample Comment*/ true

Please explain it in a detailed way.

Answer Source

HTML was originally defined formally as an application of SGML, and the comment syntax was taken from SGML. SGML uses two hyphens -- as comment delimiters, but it permits comments in certain contexts only. Of these contexts, only a comment declaration is relevant in HTML. (Well, in theory they are also allowed in entity declarations like <!ENTITY foo "foo" -- Comment -- >, but entity declarations were never implemented in any browser before XHTML, and in XHTML, following XML syntax, entity declarations cannot contain comments.)

Thus, comments are only allowed in comment declarations that contain nothing but comments, e.g.

<!-- Comment one -- -- Comment two -->

Browsers actually implemented this partly in a simplified (wrong) way, so the practical recommendation is to have comments only in comment declarations that contain a single comment:

<!-- Comment -->

Comment declarations are at the same structural level as tags and therefore cannot appear within tags. (Comments cannot contain tags either: anything that would otherwise constitute a tag, like <p>, is taken just as character data when inside a comment.)

This has not been changed in later HTML versions. They have simplified the syntax in matters like this, not extended.