Question

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.

Was it helpful?

Solution

You could use following snippet:

DEMO jsFiddle

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top