Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 734
Steve Avatar asked Jul 13 '13 02:07

Steve


People also ask

What does outerHTML return?

Value. Reading the value of outerHTML returns a string containing an HTML serialization of the element and its descendants. Setting the value of outerHTML replaces the element and all of its descendants with a new DOM tree constructed by parsing the specified htmlString .

What does outerHTML mean?

The outerHTML is the HTML of an element including the element itself. Contrast this with the innerHTML of the element, which is the HTML contained within an elements opening and closing tags. By definition, elements without both opening and closing tags do not have innerHTML.

What is the difference between innerHTML and outerHTML?

The outerHTML is the HTML of an element including the element itself. Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.

What is outerHTML in jquery?

The outerHTML is often used to replace the element and its contents completely. It differs from the innerHTML as innerHTML only represent the HTML of contents of an element, while outerHTML includes the HTML of element itself with its descendants.


2 Answers

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.

like image 138
Zhanger Avatar answered Sep 18 '22 01:09

Zhanger


HTML comments are part of the DOM, they just get ignored by the browser for display.

like image 32
Vaishak Suresh Avatar answered Sep 20 '22 01:09

Vaishak Suresh