Home > Mobile >  Why is Comment an interface/class?
Why is Comment an interface/class?

Time:09-18

I'm a beginner in web development so I was reading MDN Web Docs and Chromium source code in order to understand how Javascript DOM HTML element classes work and are implemented and I found out that HTML comment elements are actually interfaces/classes (i don't know why in MDN it's called an interface if it has a constructor) (https://developer.mozilla.org/en-US/docs/Web/API/Comment). Why is it made that way? Isn't it a waste of space?

CodePudding user response:

The "interface" (of a comment node) being referred to is the description of its properties methods and/or nature provided using IDL ("interface definition language") within a specification. In other words "interface" as used here means "what it exposes, if anything" and, by implication, how it works.

Be wary of interpreting "interface" in the context of an IDL definition in the context of a programming language - the whole idea of IDL is to allow specifications to be written independently of specific programming languages.

You can read the specification of the comment interface in the DOM3 specification here.

CodePudding user response:

Unlike in many languages, HTML comments are part of the mark-up. You can dynamically generate them and insert them into the DOM, just like you can do with any other node.

This can potentially be useful, for example, by libraries which modify the DOM but wish to preserve comments for readability purposes. Some frameworks actually use comments to help them keep track of different nodes or lists of nodes.

Here's an example of how you might dynamically generate a comment within the HTML of a webpage. if you run these two lines in any webpage, you'll find a new <!-- Hello World! --> comment at the bottom of the body element:

const myComment = new Comment('Hello World!')
document.body.appendChild(myComment)

The ability to preserve comments actually isn't unique to HTML, other markup-parsing libraries will provide you with this kind of ability, precisely for the purposes of preserving them as you dynamically modify the markup. For example, see this yaml parser, which will automatically preserve the comments for you as it parses.

  • Related