Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

Read HTML Comments with JS or Jquery

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.

Upvotes: 3

Views: 4048

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

You could use following snippet:

DEMO jsFiddle

$.fn.getComments = function () {
    return this.contents().map(function () {
        if (this.nodeType === 8) return this.nodeValue;
    }).get();
}

Upvotes: 12

mingos
mingos

Reputation: 24502

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.

Upvotes: 3

Related Questions