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.

Était-ce utile?

La solution

You could use following snippet:

DEMO jsFiddle

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top