Search code examples
javascriptjqueryhtmlouterhtml

Why does outerHTML bring back <!-​- --> comments?


I have a jsfiddle here - http://jsfiddle.net/stevea/QpNbu/3/ - that collects the outerHTML for all elements that have class='active'. What amazes me is that even if I comment out some of the HTML, as in:

<!--      <div>'Some inner text'</div>  -->

outerHTML still brings it back! This can't still be in the DOM so I'm wondering where outerHTML is looking.

Thanks for any insight.


Solution

  • Comments in HTML are surprisingly, in fact, part of the DOM! If you look in this screen shot here:

    web inspector

    You'll see the google chrome web inspector renders it as part of the DOM (notice how the bottom bar shows it as a child of div#box1.active as well.)

    For more concrete documentation, if you look at the possible Node.nodeTypes for DOM nodes on MDN, you'll see that the COMMENT_NODE is one of the valid types.

    COMMENT_NODE 8

    W3 also defines the Comment interface for the DOM:

    This interface inherits from CharacterData and represents the content of a comment, i.e., all the characters between the starting '<!--' and ending '-->'. Note that this is the definition of a comment in XML, and, in practice, HTML, although some HTML tools may implement the full SGML comment structure.