3

Is it possible to read a comment written in HTML? I guess comments do not form part of the DOM therefore selecting them or evening assigning classes or id's might not be an option.

Is there any way to like read the content of the body and obtain an array of comments or something like that? Jquery is ok.

I want to create a plugin or function to do something like this:

<!-- top -->
<div>top stuff</div>

<!-- Content -->
<div>content stuff</div>

<script>

   var comments = $('body').getComments();
   alert(comments[0]); //returns "top"
   alert(comments[1]); //return "Content"
</script>

Thanks.

multimediaxp
  • 9,348
  • 13
  • 49
  • 80
  • Take a look a this: [Get text inside HTML comment tag?](http://stackoverflow.com/questions/16753384/get-text-inside-html-comment-tag) But I don't know if you may have problems in older IE (I think there was something about it, but I don't find any thing right now that would proof that) – t.niese Mar 21 '14 at 14:56

2 Answers2

12

You could use following snippet:

DEMO jsFiddle

$.fn.getComments = function () {
    return this.contents().map(function () {
        if (this.nodeType === 8) return this.nodeValue;
    }).get();
}
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Nice, swift piece! Just tried this variation of your answer `alert($('body').getComments()[0])`, `alert($('body').getComments()[1])` – guest271314 Mar 21 '14 at 15:21
3

Here's the output of my Firebug console:

>>> document.body.innerHTML = '<!-- comment -->';
"<!-- comment -->"

>>> document.body.childNodes
NodeList[Comment { data=" comment ", length=9, nodeType=8, more...}]

>>> document.body.childNodes[0]
Comment { data=" comment ", length=9, nodeType=8, more...}

>>> document.body.childNodes[0].data
" comment "

In short, JavaScript's DOM will pick up comments just as any other tags. They will be of type Comment. You can look up their data property to get the comment contents.

[EDIT]

I haven't checked this in any browsers other than Firefox 26; you might want to investigate a bit.

mingos
  • 23,778
  • 12
  • 70
  • 107